Search code examples
reactjsreact-hooksreact-propsuse-state

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


Solution

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