← react hacks / react / handling-array-state-updates-immutably.md

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.

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.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

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

Can you stay a bit longer?