bhylu.com

Advertisements

React State Update Queue

Use updater functions when several changes depend on the latest queued state.

How it works

React can batch updates from an interaction. Three calls to setCount(count + 1) all use the same render snapshot, so they do not mean “add three”. An updater receives the value produced by earlier queued updates. Keep that updater pure: it may be called more than once during development checks. The example models a small inspection batch and adds exactly three without relying on synchronous rendering.

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 [count, setCount] = useState(0);
  function inspectBatch() {
    setCount((value) => value + 1);
    setCount((value) => value + 1);
    setCount((value) => value + 1);
  }
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <button onClick={inspectBatch}>Inspect a batch of three</button>
      <output>Inspected: {count}</output>
    </main>
  );
}

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

Expected result

One click gives three inspected items; a second click gives six.

Each updater transforms its input and returns a number. React can evaluate that queue without any network request or mutation hidden inside it. A direct setCount(count + 3) is also fine when the whole decision uses this event’s snapshot; the queue is shown to make previous-value updates concrete. Prefer the expression that states the domain action most clearly.

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

Advertisements