Reputation: 101
I want to use hooks with multiple states.
const [val, setVal] = useState({
first: 0,
second: 0,
third: 0,
});
//first method
const change = () => {
// first method
setVal({
...val,
first: val["first"] + 1,
second: val["second"] + 1,
third: val["third"] + 1,
});
// second method
setVal((data) => ({
...data,
first: val["first"] + 1,
second: val["second"] + 1,
third: val["third"] + 1,
}));
};
here is my example code.
Both the first and second methods have the same results.
I know, In React Docs, Second Method is recommended. But i think if i use first method, i can save one function call.
so why react recommend second method and what is the main differences between first and seconds.
Thanks!
Upvotes: 0
Views: 34
Reputation: 617
If you call "setVal" fast enough, there is chance that accessing val would get incorrect value. If you pass function to the setter, data would be in correct state, so incrementing self should be like this:
// data is previous state here
setVal((data) => ({
...data, // This is unnecessary as you overwrite all of the values
first: data["first"] + 1,
second: data["second"] + 1,
third: data["third"] + 1,
}));
I would also recommend using useReducer in case there are multiple state values.
Here is example of broken setState (click multiple times) https://codesandbox.io/s/use-state-broken-0q994 Changing to this
setCount((count) => count + 1);
Would fix the problem.
Upvotes: 1