0 day streak
javascript / beginner
Snippet

Adding Items to Arrays (Spread)

To update an array in React state, you must create a new array. The spread operator (...) copies the old items into a new list alongside the new item.

snippet.js
javascript
1
2
3
4
5
const [list, setList] = useState(['Apple']);
const addFruit = (newFruit) => {
setList([...list, newFruit]);
};
react
Breakdown
1
...list
The spread operator 'unpacks' the existing items from the original array.
2
[...list, newFruit]
Creates a completely new array containing all old items plus the new one.