close

How can I update the parent’s state in React?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I update the parent’s state in React? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I update the parent’s state in React ?

  1. How can I update the parent's state in React ?

    can I update the parent's state in React Most of the answers given previously are for React.Component-based designs. If you are using useState in the recent upgrades of the React library

  2. How can I update the parent's state in React ?

    can I update the parent's state in React Most of the answers given previously are for React.Component-based designs. If you are using useState in the recent upgrades of the React library

Method 1

This is how we can do it with the new useState hook. Method – Pass the state changer function as a props to the child component and do whatever you want to do with the function

import React, {useState} from 'react';

const ParentComponent = () => {
  const[state, setState]=useState('');
  
  return(
    <ChildConmponent stateChanger={setState} />
  )
}


const ChildConmponent = ({stateChanger, ...rest}) => {
  return(
    <button onClick={() => stateChanger('New data')}></button>
  )
}

Method 2

Most of the answers given previously are for React.Component-based designs. If you are using useState in the recent upgrades of the React library

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment