Immutable Array State Updates in React
When working with React, updating the state immutably is a key best practice. Let's see how to handle array state updates immutably.
Consider an array state:
const [items, setItems] = useState(['Apple', 'Banana', 'Cherry']);
To add an item:
setItems(prevItems => [...prevItems, 'Date']);
To remove an item:
setItems(prevItems => prevItems.filter(item => item !== 'Banana'));
To update an item:
setItems(prevItems => prevItems.map((item, index) => index === 1 ? 'Blueberry' : item));
In each case, we're creating a new array instead of mutating the existing one. This allows React to optimize re-rendering and helps prevent hard-to-find bugs related to mutable state.
Explore more articles
Keep experimenting and happy coding! You can find me at @samuellawrentz on X.