Immutable Array State Updates in React

Learn how to handle array state updates immutably in React. Get best practices and code snippets to improve your React development skills.

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

00:00

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

Can you stay a bit longer?