8 ms·
I don't use react but... isn't his solution also wrong? function handleAddItem(value) { const nextItems = [...items, value]; setItems(nextItems); }
by react_noob 4y ago
I don't use react but... isn't his solution also wrong?
function handleAddItem(value) {
const nextItems = [...items, value];
setItems(nextItems);
}
should be?
function handleAddItem(value) {
setItems(items => [...items, value]);
}
- reducesuffering 4y agoNo, you can provide the state setter, setItems, with a new copy of the state object itself. Doesn't need to be a function.
- simple-thoughts 4y agoBoth are valid, but you’re right in that, at least in my experience, the second option can be safer. Specifically when updating an object or list via an asynchronous call where the calls can change based on state (such as the user changing accounts)
- jameshart 4y agoIf there are no other ways to update that state, the example will work fine. It might come back and bite you if you implement something that performs an async update of that state via a different path later.
- erikpukinskis 4y agoIn my experience, that form of useState is an anti-pattern… It’s not that it doesn’t work, it does. But I’ve found there are basically two scenarios: 1) Simple cases where there’s no risk of contention and you can just operate as if your state variable is up-to-date. 2) Complex cases where you have state changes coming from multiple directions and contention is a concern. In the second scenario I just go straight to useReducer. It is much more reliable than useState when there is the possibility of contention. And it’s much easier to reason about than having a bunch of setState calls all over. IMO the setState((oldState) => newState) pattern is a half measure that’s almost never the best choice.
- throwaway290 4y agoWell put, have the same feeling. Any thought on signals? They seem to be hyped as the next big thing for managing state, haven't used them myself yet though.
- erikpukinskis 4y agoFor me the most important thing in a React app is to maintain readability, and I think the functional control flow helps with that. My initial reaction to signals is that they’ll hurt that readability. But I haven’t used them personally so I don’t know. Will be interesting to see how folks do with them.