Skip to content

From useState to useReducer

The Course
•
20 min study

The reducer

A reducer takes the current state and an action, an object describing what happened, and returns the next state:

JavaScript
export function boardReducer(cards, action) {
  switch (action.type) {
    case "card_added":
      return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }];
    case "card_moved":
      return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card));
    case "card_removed":
      return cards.filter((card) => card.id !== action.id);
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}

It's the same new-array code you'd write with useState. Here is the useState version of the same board, for comparison:

JavaScript
const [cards, setCards] = useState(starterCards);

function addCard(title, minutes) {
  setCards([...cards, { id: Date.now(), title, column: "todo", minutes }]);
}

function moveCard(id, column) {
  setCards(cards.map((card) => (card.id === id ? { ...card, column } : card)));
}

function removeCard(id) {
  setCards(cards.filter((card) => card.id !== id));
}

Each case in the reducer is one of these handlers' bodies. The code has just moved out of the handlers and into one place, in its own file, with no React in it.

useReducer

JavaScript
const [cards, dispatch] = useReducer(boardReducer, starterCards);
  • useReducer takes the reducer and the starting state.
  • It returns the current state and a dispatch function.
  • To change state, dispatch an action:
JavaScript
dispatch({ type: "card_moved", id, column });

React calls boardReducer(cards, action), stores what it returns, and re-renders. Event handlers no longer say how to change the cards, only what happened.

The board with a reducer React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function AddCard({ onAdd }) { const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim(), 15); setTitle(""); } return ( <form className="toolbar" onSubmit={handleSubmit}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> </form> ); } import { useReducer } from "react"; import AddCard from "./AddCard.jsx"; import Board from "./Board.jsx"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, dispatch] = useReducer(boardReducer, starterCards); return ( <main> <h1>Study Board</h1> <AddCard onAdd={(title, minutes) => dispatch({ type: "card_added", id: Date.now(), title, minutes })} /> <Board cards={cards} onMove={(id, column) => dispatch({ type: "card_moved", id, column })} onRemove={(id) => dispatch({ type: "card_removed", id })} /> </main> ); } import { columns } from "./data.js"; export default function Board({ cards, onMove, onRemove }) { return ( <div className="board"> {columns.map((column, index) => { const inColumn = cards.filter((card) => card.column === column.id); const next = columns[index + 1]; return ( <section key={column.id} className="column"> <h2> {column.title} <span className="count">({inColumn.length})</span> </h2> <ul className="cards"> {inColumn.map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => onMove(card.id, next.id)} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => onRemove(card.id)} aria-label={`Remove ${card.title}`}>×</button> </li> ))} </ul> </section> ); })} </div> ); } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Add a card, move cards with →, and remove one with ×. Then read App.jsx to see each button's action.

Why the id comes from the handler

card_added carries its id, made with Date.now() in App. Why not create it inside the reducer? A reducer must be pure: the same state and action must always give the same result. A timestamp depends on when the reducer runs, rather than only on its inputs. Reducers that depend on time, random numbers or the network behave unpredictably, so anything like that happens in the event handler, and goes into the action:

JSX
<AddCard onAdd={(title, minutes) => dispatch({ type: "card_added", id: Date.now(), title, minutes })} />

useState or useReducer?

useStateuseReducer
Good forA few independent values with simple updatesSeveral kinds of update to the same state
Update logic livesIn each event handlerIn one reducer function
Testing the logicThrough the componentAs a plain function, with no React (lesson 3)

Both are fine. Switch when the handlers start repeating each other, or when a bug is hard to track down because updates are scattered.

Your turn

Exercise

Rename a card

Add a card_renamed action that sets a card's title to the action's title. To try it without building a text box, give each card in Board.jsx a ! button, labelled Mark ${card.title} urgent for screen readers, that renames the card to its current title with ! on the end. Click ! twice on Read about reducers: it should read Read about reducers!!, and no other card changes.

Your working space React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function AddCard({ onAdd }) { const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim(), 15); setTitle(""); } return ( <form className="toolbar" onSubmit={handleSubmit}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> </form> ); } import { useReducer } from "react"; import AddCard from "./AddCard.jsx"; import Board from "./Board.jsx"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, dispatch] = useReducer(boardReducer, starterCards); return ( <main> <h1>Study Board</h1> <AddCard onAdd={(title, minutes) => dispatch({ type: "card_added", id: Date.now(), title, minutes })} /> <Board cards={cards} onMove={(id, column) => dispatch({ type: "card_moved", id, column })} onRemove={(id) => dispatch({ type: "card_removed", id })} /> </main> ); } import { columns } from "./data.js"; export default function Board({ cards, onMove, onRemove }) { return ( <div className="board"> {columns.map((column, index) => { const inColumn = cards.filter((card) => card.column === column.id); const next = columns[index + 1]; return ( <section key={column.id} className="column"> <h2> {column.title} <span className="count">({inColumn.length})</span> </h2> <ul className="cards"> {inColumn.map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => onMove(card.id, next.id)} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => onRemove(card.id)} aria-label={`Remove ${card.title}`}>×</button> </li> ))} </ul> </section> ); })} </div> ); } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

A rename changes one field of one card; every other card stays as it was. One of the existing actions already does exactly that to a different field. The new title is worked out in the event handler and carried in the action, just as card_added carries its id.

Hint 2: a first step

Start from the outside in. Give Board an onRename prop, have App pass a function that dispatches card_renamed with an id and a title, and add the button. Click it: the lab stops with Unknown action: card_renamed, from the reducer's default case. That error tells you where the last piece goes.

Show one solution

In boardReducer.js:

JavaScript
case "card_renamed":
  return cards.map((card) => (card.id === action.id ? { ...card, title: action.title } : card));

In App.jsx:

JavaScript
onRename={(id, title) => dispatch({ type: "card_renamed", id, title })}

In Board.jsx, add onRename to the props and a button to each card:

JSX
<button onClick={() => onRename(card.id, card.title + "!")} aria-label={`Mark ${card.title} urgent`}>!</button>

The reducer doesn't know about exclamation marks: it just sets the title it's given. A real rename box would dispatch the same action with whatever was typed.

Was this article helpful?

Your response is saved on this device.