javascript / beginner
Snippet
The Spread Operator for Arrays
In React, we must never change (mutate) arrays directly. The spread operator (...) creates a new copy of the array and adds the new item, which is the correct way to update data.
snippet.js
1
2
3
4
const addItem = (oldItems, newItem) => {const updatedItems = [...oldItems, newItem];return updatedItems;};
react
Breakdown
1
[...oldItems, newItem]
Copies all elements from 'oldItems' into a new array and appends 'newItem'.