Reading questions about useState hook I was thinking about setState. I'm always using intentionally the setState with the callback option to access the previous state and have all the elements for example in an array.
So I have made a quick example for representation in a functional component:
const [elems, setElems] = useState([]);
const addElemsMutate = (count) => {
const newArray = [...elems];
for (let i = 0; i < count; i++) {
newArray.push(i);
}
setElems(newArray);
};
const addElemsUsePreviousState = (count) => {
for (let i = 0; i < count; i++) {
setElems(previousElems => [...previousElems, i]);
}
}
return <>
<button onClick={() => addElemsMutate(10)}>addElemsMutate</button>
<button onClick={() => addElemsUsePreviousState(10)}>addElemsUsePreviousState</button>
{elems.map((e, index) => <span key={index}>{e}</span>)}
</>
Question
I understand the setState is asynchronous, enqueues changes and it should not be directly mutated as the documentation states.
The result form both of the actions look the same on the UI. So my question is about what I have in addElemsMutate function:
- Is that considered a bad practice?
- What is the downside if I'm using still that option if there is any?
Thanks!