Immutable Array State Updates in React

web development

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 =>, 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.

Keep experimenting and happy coding! You can find me at @samuellawrentz on X.

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?