Reputation: 33
I watch course about react js and And in it Adds a new item to the array(hook) as follows:
useState([new item , old Array]);
But I repeat this, the array turns into an object
Whatever I searched for, I saw the following result:
useState([ old array ,new item ]);
But the method worked well in the course
Upvotes: 3
Views: 2039
Reputation: 397
A better way of updating an array using react-hooks is to pass in a callback function to the hook, like this:
setState((oldState) => [...oldState, newItem])
This is considered a best practice and is a lot more performant than directly spreading the old state.
Upvotes: 1
Reputation: 71
You should use the spread operator: setState(prev => [...prev, newItem]);
Upvotes: 2
Reputation: 975
To add items to an array using React hooks you need to use the spread operator to get the old array and then add the new item.
setState([...oldArray, newItem])
Upvotes: 2