Mario.Ds
Mario.Ds

Reputation: 33

add item to array(Hooks) react js

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

Answers (3)

Fardeen Panjwani
Fardeen Panjwani

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

Aleksandr Bagrintsev
Aleksandr Bagrintsev

Reputation: 71

You should use the spread operator: setState(prev => [...prev, newItem]);

Upvotes: 2

Sean
Sean

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

Related Questions