3 ms·
setState({...state, foo: "bar"}) The code you presented is wrong - it won't work the way you expect. Or worse, it might work the way you expect, by chance. I
by andrewstuart 5y ago
setState({...state, foo: "bar"})
The code you presented is wrong - it won't work the way you expect. Or worse, it might work the way you expect, by chance.
If you wish to use the previous state you must do it this way:
setState(prevState => ({...prevState, foo: "bar"}))
- Waterluvian 5y agoThanks. Most importantly, though: why? Is there some race condition about updates or bulk updating?
- andrewstuart 5y agoBriefly - it is because React batches and executes setState calls some time in the future - thus you MUST use a function call to get a non-stale state. Refer to my more detailed explanation elsewhere in this thread.
- Waterluvian 5y agoThanks. I see the example in the docs shows this method. StackOverflow shows many people sharing the same. I’ve never had this problem so I’m probably quite lucky. But it makes complete sense. I’m surprised it’s not called out on the docs page for setState.
- andrewstuart 5y ago>> I’ve never had this problem so I’m probably quite lucky. Possibly, but more likely you've had weird bugs that never quite made sense and eventually things seemed to work so you moved on, but what was actually happening was a stale state problem. It's hard to write big React apps using the wrong way to udpate setState without bugs.