How to Add Item to Array in State React: Simple Guide
In React, to add an item to an array in state, use the
useState hook and update the state by creating a new array with the existing items plus the new item using the spread operator, like setArray([...array, newItem]). This ensures React detects the change and re-renders the component.Syntax
Use the useState hook to hold the array state. To add an item, call the setter function with a new array that includes all old items plus the new one.
array: current state arraysetArray: function to update the statenewItem: the item to add[...array, newItem]: creates a new array with old items and the new item
javascript
const [array, setArray] = useState([]); // To add an item: setArray([...array, newItem]);
Example
This example shows a button that adds a new number to the array in state each time it is clicked. The list updates to show all numbers.
javascript
import React, { useState } from 'react'; export default function AddItemExample() { const [numbers, setNumbers] = useState([1, 2, 3]); function addNumber() { const nextNumber = numbers.length + 1; setNumbers([...numbers, nextNumber]); } return ( <div> <button onClick={addNumber}>Add Number</button> <ul> {numbers.map(num => ( <li key={num}>{num}</li> ))} </ul> </div> ); }
Output
<button>Add Number</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Common Pitfalls
One common mistake is trying to modify the state array directly, like using array.push(newItem), which does not create a new array and can cause React not to update the UI. Always create a new array using the spread operator or methods like concat.
Also, avoid setting state based on the current state without using a function updater when the new state depends on the old state, to prevent stale closures.
javascript
/* Wrong way - mutates state directly */ array.push(newItem); setArray(array); // ❌ /* Right way - creates new array */ setArray([...array, newItem]); // ✅ /* Using function updater to avoid stale state */ setArray(prevArray => [...prevArray, newItem]); // ✅
Quick Reference
- Use
useStateto hold array state. - Update state by creating a new array with
[...oldArray, newItem]. - Use function updater
setArray(prev => [...prev, newItem])when new state depends on old state. - Never mutate state directly (no
pushor direct assignment).
Key Takeaways
Always create a new array when updating state to trigger React re-render.
Use the spread operator to add items: setArray([...array, newItem]).
Use function updater form when new state depends on previous state.
Never mutate the state array directly with methods like push.
React state updates must be immutable to work correctly.