3

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

3 Answers 3

2

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])

Sign up to request clarification or add additional context in comments.

1 Comment

@Morteza.s17 make sure you use the setState function and not useState when updating it which is what you have in your question
2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.