How to Use useState with Array in React
Use
useState to store an array by initializing it with an array value. Update the array state by creating a new array (e.g., with spread syntax) and passing it to the setter function to keep React state immutable.Syntax
The useState hook returns a state variable and a function to update it. When using an array, initialize the state with an array value. To update, create a new array and pass it to the setter to avoid mutating the original state.
const [array, setArray] = useState(initialArray): declares state.setArray(newArray): updates state with a new array.
javascript
const [items, setItems] = useState([]); // To add an item: setItems(prevItems => [...prevItems, newItem]);
Example
This example shows a React component that manages a list of fruits. It uses useState to hold an array and adds new fruits when a button is clicked.
javascript
import React, { useState } from 'react'; function FruitList() { const [fruits, setFruits] = useState(['Apple', 'Banana']); const addFruit = () => { setFruits(prevFruits => [...prevFruits, 'Orange']); }; return ( <div> <h3>Fruits:</h3> <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> <button onClick={addFruit}>Add Orange</button> </div> ); } export default FruitList;
Output
Fruits:
- Apple
- Banana
[Button: Add Orange]
(Clicking button adds 'Orange' to the list)
Common Pitfalls
Common mistakes include mutating the array directly instead of creating a new one, which prevents React from detecting changes and updating the UI.
Always use methods like spread syntax or array methods that return new arrays.
javascript
const [numbers, setNumbers] = useState([1, 2, 3]); // Wrong: mutating original array // numbers.push(4); // setNumbers(numbers); // React may not update // Right: create new array setNumbers(prev => [...prev, 4]);
Quick Reference
| Action | Example Code | Description |
|---|---|---|
| Initialize array state | const [arr, setArr] = useState([]); | Start with an empty or preset array. |
| Add item | setArr(prev => [...prev, newItem]); | Add new item immutably. |
| Remove item | setArr(prev => prev.filter(item => item !== target)); | Remove items by filtering. |
| Update item | setArr(prev => prev.map(item => item.id === id ? newItem : item)); | Update items immutably. |
Key Takeaways
Always treat array state as immutable by creating new arrays when updating.
Use the setter function from useState to update the array state.
Avoid mutating the original array directly to ensure React re-renders.
Use spread syntax or array methods like filter and map to create new arrays.
Initialize useState with an array to store list data.