Wanting to improve my understanding of React in functional components I've seen some that pass a seState
with a function when spreading an array or object. When I reference the docs I see:
Unlike the
setState
method found in class components,useState
does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax
So I'm trying to understand why this implementation:
const [count, setCount] = useState([initialCount]);
setCount([...count, newCount])
is not the preferred when it comes to arrays and objects and this:
const [count, setCount] = useState([initialCount]);
setCount(prevCount => [...prevCount, newCount])
is the preferred. In my research for an answer I haven't found an answer about this and I've read through:
- What is the equivalent of passing an updater to
setState
that takes(state, props)
as an argument to update state, using React Hook? - How to use callback with useState hook in react
- setState with spread operator
The only conclusions I can establish the need for the function is:
- possibly due to the way the object or array is stored in memory
- size of the data being passed
Why when it comes to arrays and objects in a useState
it should be passed with a function opposed to what's commonly used?