2 ms·
I like the `extendState` concept. So far, most of the time, I find that modern JS is fine enough. I can absolutely see the benefit of abstracting this concept.
by Waterluvian 5y ago
I like the `extendState` concept. So far, most of the time, I find that modern JS is fine enough. I can absolutely see the benefit of abstracting this concept. But I'm always hesitant to layer on top of an API just for little improvements. The cost is deceptively high: you have to re-remember your custom API and others have to learn your custom API.
setState({...state, foo: "bar"})
- andrewstuart 5y agosetState({...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.