olayemii
olayemii

Reputation: 600

Using useState() with an object as state

I am trying to use the setState react hook and I am trying to make an object of states for different states like this

const [myState, setMyState] = useState({bulb1state: true, bulb2state: true})

then i try to change the states by doing:

setMyState({...myState, bulb1state: false})
//My state is now {bulb1state: false, bulb2state: true } 

which is normal and expected, but when i try to set the other state of the object by doing

setMyState({...myState, bulb2state: false})
//My state now becomes {bulb1state: true, bulb2state: false } 

I was expecting

{bulb1state: false, bulb2state: false } 

What could be the cause? is this normal or is this because of the asynchronous way states work?

Upvotes: 2

Views: 80

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85102

My best guess is that you have a function which is closing over an obsolete version of the state. I'd have to see the rest of the code surrounding your use of setMyState to be sure.

Regardless, you should be able to fix it by using the callback version of setMyState to make sure you have the latest state:

setMyState(prevState => ({
  ...prevState, 
  bulb2state: false
});

Upvotes: 7

Related Questions