← 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. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

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

    tag: reacttag: web developmenttag: performance optimization

00:00

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

Can you stay a bit longer?