Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useState with state that updates based on props [duplicate]

I have a functional React component that roughly looks like this:

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)  

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}

This obviously doesn't work because React only computes the initial state part once, so myState isn't updated on prop1 change.

Is there a way to make this work without using useReducer? Is this a good use case for useEffect?

like image 416
internet Avatar asked Oct 20 '25 09:10

internet


1 Answers

This is because state is only initialized once. That's why the second value returned from useState() is a setter function. It's intended to be the only way to update the state after initialization. In this case you would use a useEffect() hook to update the state when props change (although there's not generally a great reason to initialize state with a prop).

const MyComponent = (prop1) => {
  
  const [myState, setState] = useState(prop1)

  useEffect(() => {
    setState(prop1)
  }, [prop1])

  return <>
    {myState && <div>Some text...</div>}
    <div onClick={() => setState(true)}>Click me</div>
  </>
}
like image 119
Keith Brewster Avatar answered Oct 21 '25 22:10

Keith Brewster