React Mastery / React Hooks

useState with Array

๐Ÿ”น What is useState with Arrays?

In React, useState can store arrays when you need to manage a list of data, such as:

  • Todo lists

  • Shopping carts

  • Users list

  • Dynamic UI elements

โš ๏ธ Arrays in state should never be mutated directly.


๐Ÿ”น Basic Syntax

const [items, setItems] = useState([]);
  • items โ†’ current array

  • setItems โ†’ function to update array

  • Updating state replaces the old array


๐Ÿ”น Simple Example

import { useState } from "react";

function Fruits() {
  const [fruits, setFruits] = useState(["Apple", "Banana"]);

  return (
    <div>
      <ul>
        {fruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>

      <button onClick={() => setFruits(["Apple", "Banana", "Orange"])}>
        Add Orange
      </button>
    </div>
  );
}

๐Ÿ”น Adding Items to an Array

โœ… Correct Way (using spread operator)

setItems([...items, newItem]);

Example

const addItem = () => {
  setFruits([...fruits, "Mango"]);
};

๐Ÿ”น Using Functional Update (Best Practice)

setItems(prevItems => [...prevItems, newItem]);

โœ… Why?

  • Uses latest state

  • Avoids stale state bugs

  • Recommended for real apps


๐Ÿ”น Removing an Item from Array

const removeItem = (itemToRemove) => {
  setItems(items.filter(item => item !== itemToRemove));
};

Example

<button onClick={() => removeItem("Apple")}>
  Remove Apple
</button>

๐Ÿ”น Updating an Item in an Array

Example: Update by index

const updateItem = (index) => {
  setItems(items.map((item, i) =>
    i === index ? "Updated Item" : item
  ));
};

๐Ÿ”น Updating Object Inside an Array

const [users, setUsers] = useState([
  { id: 1, name: "Alex" },
  { id: 2, name: "John" }
]);

const updateUser = (id) => {
  setUsers(users.map(user =>
    user.id === id ? { ...user, name: "Mike" } : user
  ));
};

๐Ÿ”น Clearing the Array

setItems([]);

๐Ÿ”น Common Mistakes

โŒ Mutating Array Directly

items.push("New Item");
setItems(items); // โŒ wrong

โŒ Using Index as Key (Anti-pattern)

items.map((item, index) => <li key={index}>{item}</li>)

โœ”๏ธ Use unique IDs instead


๐Ÿ”น Correct Way to Use Keys

items.map(item => <li key={item.id}>{item.name}</li>)

๐Ÿ”น When to Use Array State?

โœ… Use when:

  • Managing dynamic lists

  • Rendering repeated components

โŒ Avoid when:

  • State becomes deeply nested โ†’ split state or use reducer



๐Ÿ”น State Used

State

Purpose

todos

Stores todo list

text

Input value

editId

Tracks which todo is being edited


๐Ÿง  Key Concepts Used

  • useState with array of objects

  • Controlled inputs

  • Conditional rendering

  • map() & filter()

  • Immutable state updates