I have code example like this (codesandbox demo):
const [array, setArray] = useState([]);
const addElementToArray = () => {
array.push(1);
setArray([...array]);
}
return (
<div className="App">
<button onClick={addElementToArray}>addElementToArray</button>
{array.map(el => <div>{el}</div>)}
</div >
);
Here I dont use standard way of updating array like
setArray([...array, 1]);
What disadvantages of updating values like in my first example?
CodePudding user response:
In this example you won't notice any problems. But then, this is a very small and contrived example, isn't it?
But in a larger application with more complex logic and functionality, this can easily lead to strange and difficult bugs. Why? Because you're directly mutating state:
array.push(1);
Does anything else hold a reference to that state or observe it in any way? Is this mutation happening in the middle of a component render, where some logic has already responded to the pre-mutated state and the remaining logic will respond to the post-mutated state? Are multiple state updates being queued and now we don't know which ones will see which version of state?
That's a lot to have to keep track of. Or you can avoid all of those potential problems by simply not mutating state and sticking with "the standard way" that you already know:
setArray([...array, 1]);
or, if there may be multiple state updates and you want to append the 1
to the most current:
setArray(a => [...a, 1]);
CodePudding user response:
If you use this line alone,
array.push(1);
the state changes but React isn't aware of the change so the component won't rerender. In this case, the whole purpose of React is gone because the UI does not correspond to the state change, and that makes it a bad practice.
However, if you use this line alone:
setArray([...array, 1]);
the UI will correspond to the state change, which is the correct way of using React.
And regarding this:
array.push(1);
setArray([...array]);
you're basically mocking React because .push()
changes the state without any rerender.