0

I have a functional component and am using useState to store some values in an object. No matter what, on re-render, the object seems to be wiped and then set to the initial value. But if I store, e.g. a simple string, it behaves as expected.

MyCompontent = (props) => {

  const [name,setName] = useState('Bob')
  const [stateDict,setStateDict] = useState({
    number: 1, 
    color: green,
    somethingElse: undefined,
    aFourthThing: {}
  })

  console.log(`${name}, ${number}`)
  //first pass, name is Bob, number is 1
  //second pass, name changes to Fred, number is still 1

  if (name == "Bob") { setName("Fred") }
  
  if (stateDict.number == 1) { 
   setStateDict({...stateDict,  number: 2})
  }

}

What about the Object in state makes it behave differently? Or am I doing my update incorrectly? I followed some other SO posts on how to store objects in state.

enesefuu
  • 369
  • 4
  • 14
  • 1
    Why do you need to access the variable above the hook call? The variable isn't defined on any call until the `useState` line, as you've seen. – ggorlen Aug 29 '21 at 23:28
  • https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone – ksav Aug 30 '21 at 00:10
  • You should get a `reference error - cannot access 'name' before initialization` – ksav Aug 30 '21 at 00:12
  • Hey @ggorlen -- I was misunderstanding what was going on. There is still something weird going on, but I updated the post to reflect the actual problem. Thanks for the help! – enesefuu Aug 30 '21 at 15:48
  • Set the state inside a `function` or `useEffect` hook, why are you doing it inside the body of the main function? – Rajendran Nadar Aug 30 '21 at 15:53
  • Can you share a runnable [mcve] as a [stack snippet](https://meta.stackoverflow.com/questions/338537/how-do-i-create-a-react-stack-snippet-with-jsx-support/338538#338538)? I don't see a problem with this code other than `green` being undefined, which I assume is unintentional. Maybe this is the problem? [Multiple calls to state updater from useState in component causes multiple re-renders](https://stackoverflow.com/questions/53574614/multiple-calls-to-state-updater-from-usestate-in-component-causes-multiple-re-re) – ggorlen Aug 30 '21 at 16:02

0 Answers0