bhylu.com

Advertisements

React useReducer

Use a reducer when several operations should follow one small set of update rules.

How it works

useReducer separates the current state from the function that calculates its next value. An action names what happened; the reducer decides how that event affects state. The reducer must be pure and return a valid state for every action it accepts. Here the local selection count cannot go below zero or above three. Keeping that boundary in one function makes button logic and tests simpler.

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, useReducer } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

export function selection(state, action) {
  if (action.type === 'add') return Math.min(3, state + 1);
  if (action.type === 'remove') return Math.max(0, state - 1);
  if (action.type === 'reset') return 0;
  return state;
}
function App() {
  const [count, dispatch] = useReducer(selection, 0);
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <button onClick={() => dispatch({ type: 'remove' })}>Remove</button>
      <button onClick={() => dispatch({ type: 'add' })}>Add</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
      <output>Selected: {count}</output>
    </main>
  );
}

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

Expected result

Remove keeps zero at zero; four Add clicks stop at three; Reset returns to zero.

dispatch does not require the event handler to know the current count. The reducer owns the limit and accepts plain action objects. An unknown action leaves this small reducer unchanged; a larger domain may choose to throw during development instead. Effects and requests belong outside the reducer, with their results represented as later actions if needed.

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

Advertisements