bhylu.com

Advertisements

React Updating Arrays in State

Use map for replacement and filter for removal, keeping stable IDs across the update.

How it works

A collection update should say which record changes and what its next value is. map can replace one matching record while returning unchanged records as they are. filter can remove an ID without editing the original array. This example toggles a local checklist item. It keeps the item identity stable and calculates the completion count from the current collection rather than retaining another count in state.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function App() {
  const [items, setItems] = useState([
    { id: 'hinge', name: 'Check hinges', done: false },
    { id: 'feet', name: 'Check feet', done: false },
  ]);
  function toggle(id) {
    setItems((rows) =>
      rows.map((row) => (row.id === id ? { ...row, done: !row.done } : row)),
    );
  }
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <label>
              <input
                type="checkbox"
                checked={item.done}
                onChange={() => toggle(item.id)}
              />
              {item.name}
            </label>
          </li>
        ))}
      </ul>
      <output>
        {items.filter((item) => item.done).length} of {items.length} checked
      </output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

Ticking one row shows one of two checked; ticking it again returns the count to zero.

The checkbox is controlled by its record’s done value. The handler identifies the record by ID, not by its current position. Avoid mutating array methods on the state value: copy before sort or reverse, and create new records for changed fields. This makes undo, debugging and memoized children easier to reason about later.

For API contracts and version differences, use React’s official documentation.

Advertisements