Home > Back-end >  Is there a way to update React state in child without passing state and setter function as props?
Is there a way to update React state in child without passing state and setter function as props?

Time:10-30

i'm quite familiar with react, but i've been thinking about this one for some time. I have parent component and child component. I want to have state in form of an object in parent component and i want to set the state in child component. Problem is: Not only i need to pass setState function to child, i have to pass the state itself to spread it when updating single property in object. I could also create multiple states for properties in object, but in that case i would have to pass multiple state setters.

Is there a better way to do this?

Here is some pseudocode to better represent the issue:

const ParentComponent = () => {
   const [state, setState] = useState(a: 1, b: 2)

   return <ChildComponent state={state} setState={setState} />
}

const ChildComponent = ({state, setState}) => {

   return <button onClick={() => setState({...state, b: state.b   1})}></button>

}
 

CodePudding user response:

If you just need to update the value you can pass just the setter function and use a function inside the setState call

const ParentComponent = () => {
   const [state, setState] = useState(a: 1, b: 2)

   return <ChildComponent setState={setState} />
}
const ChildComponent = ({setState}) => {

   return <button onClick={() => setState( state => ({...state, b: state.b   1}))}></button>

}

  • Related