0
0
ReactHow-ToBeginner · 3 min read

How to Update Specific Item in Array State in React

To update a specific item in an array state in React, use the setState function with a callback that returns a new array. Use Array.map() to create a new array where only the targeted item is changed, keeping others unchanged.
📐

Syntax

Use the setState function with a callback that receives the previous state array. Inside, use Array.map() to return a new array. For each item, check if it matches the item to update; if yes, return the updated item, otherwise return the original.

This keeps state immutable and triggers React to re-render.

javascript
setArray(prevArray => prevArray.map(item => item.id === targetId ? {...item, property: newValue} : item));
💻

Example

This example shows a React component with an array of objects in state. Clicking the button updates the name of the item with id 2.

javascript
import React, { useState } from 'react';

function UpdateItemExample() {
  const [items, setItems] = useState([
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Cherry' }
  ]);

  const updateItem = () => {
    setItems(prevItems =>
      prevItems.map(item =>
        item.id === 2 ? { ...item, name: 'Blueberry' } : item
      )
    );
  };

  return (
    <div>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <button onClick={updateItem}>Update Banana to Blueberry</button>
    </div>
  );
}

export default UpdateItemExample;
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul><button>Update Banana to Blueberry</button>
⚠️

Common Pitfalls

Mutating state directly: Changing the original array or objects inside it will not trigger React to re-render. Always create a new array and new objects.

Using index as key: This can cause unexpected behavior when updating items. Use a unique id instead.

javascript
/* Wrong: mutating state directly */
setItems(prevItems => {
  prevItems[1].name = 'Blueberry';
  return prevItems;
});

/* Right: create new array and objects */
setItems(prevItems =>
  prevItems.map(item =>
    item.id === 2 ? { ...item, name: 'Blueberry' } : item
  )
);
📊

Quick Reference

  • Use setState with a function to access previous state.
  • Use Array.map() to create a new array with updated item.
  • Use object spread { ...item, property: newValue } to update item immutably.
  • Always use unique keys when rendering lists.

Key Takeaways

Always create a new array and objects to update state immutably in React.
Use Array.map() to update only the targeted item in the array state.
Pass a function to setState to safely access the previous state.
Avoid mutating state directly to ensure React re-renders correctly.
Use unique keys, not indexes, when rendering lists to prevent bugs.