0
0
ReactHow-ToBeginner · 3 min read

How to Update Array in State React: Simple Guide

To update an array in React state, use the useState hook and create a new array copy with the changes, then set it with the setter function. Avoid mutating the original array directly; instead, use methods like map, filter, or spread syntax [...array] to produce a new array.
📐

Syntax

Use the useState hook to hold your array state. To update it, create a new array with the changes and pass it to the setter function.

  • const [array, setArray] = useState(initialArray); — declares state.
  • setArray(newArray); — updates state with a new array.
javascript
const [items, setItems] = useState([]);

// To update:
setItems(newArray);
💻

Example

This example shows how to add and remove items from an array in React state using useState. It demonstrates creating a new array copy to update state without mutating the original.

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

export default function ArrayUpdateExample() {
  const [fruits, setFruits] = useState(['Apple', 'Banana']);

  // Add a fruit
  const addFruit = () => {
    setFruits(prev => [...prev, 'Orange']);
  };

  // Remove a fruit
  const removeFruit = (fruit) => {
    setFruits(prev => prev.filter(item => item !== fruit));
  };

  return (
    <div>
      <h3>Fruits:</h3>
      <ul>
        {fruits.map(fruit => (
          <li key={fruit}>
            {fruit} <button onClick={() => removeFruit(fruit)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={addFruit}>Add Orange</button>
    </div>
  );
}
Output
Fruits: - Apple Remove - Banana Remove [Add Orange button]
⚠️

Common Pitfalls

Common mistakes include mutating the original array directly, which can cause React not to detect changes and skip re-rendering.

Wrong way (mutating):

fruits.push('Orange');
setFruits(fruits);

Right way (immutable update):

setFruits(prev => [...prev, 'Orange']);

Always create a new array instead of changing the old one.

📊

Quick Reference

  • Use useState to hold array state.
  • Update arrays immutably with spread [...array], map, or filter.
  • Never mutate the original array directly.
  • Use the setter function to update state.

Key Takeaways

Always update React array state immutably by creating a new array.
Use the setter function from useState to apply updates.
Avoid mutating the original array to ensure React re-renders correctly.
Common methods for updates include spread syntax, map, and filter.
Test updates by rendering the array items in your component.