About 20 minutes of active study
Include time to predict, run, change, and explain the code. This is a suggested pace, not a time limit.
Because every change to the board goes through one reducer, adding undo is
mostly a matter of remembering earlier states. You can do it without touching
boardReducer at all.
Undo and redo React · 8 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 { createHistory, withHistory } from "./history.js";
import { starterCards } from "./data.js";
const reducer = withHistory(boardReducer);
export default function App() {
const [history, dispatch] = useReducer(reducer, starterCards, createHistory);
const cards = history.present;
return (
<main>
<h1>Study Board</h1>
<div className="toolbar">
<button onClick={() => dispatch({ type: "undo" })} disabled={history.past.length === 0}>Undo</button>
<button onClick={() => dispatch({ type: "redo" })} disabled={history.future.length === 0}>Redo</button>
</div>
<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 },
];
// Wraps any reducer so its state can be undone and redone.
export function createHistory(present) {
return { past: [], present, future: [] };
}
export function withHistory(reducer) {
return function historyReducer(history, action) {
const { past, present, future } = history;
switch (action.type) {
case "undo":
if (past.length === 0) return history;
return { past: past.slice(0, -1), present: past.at(-1), future: [present, ...future] };
case "redo":
if (future.length === 0) return history;
return { past: [...past, present], present: future[0], future: future.slice(1) };
default: {
const next = reducer(present, action);
if (next === present) return history;
return { past: [...past, present], present: next, future: [] };
}
}
};
}
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;
}
Move and remove a few cards, then press Undo and Redo .
History as state
The state is no longer just the cards. It's a history:
{ past : [ ... earlier card arrays ], present : [ ... cards now ], future : [ ... undone card arrays ] }
A normal action runs the board reducer on present, pushes the old present
onto past, and clears future. A new change after an undo throws away the
redo steps, as in every editor.
Undo moves the last of past into present, and the old present to the
front of future.
Redo does the opposite.
Nothing is changed in place. Each step makes new arrays, so the old card arrays
in past are exactly as they were.
A reducer that wraps a reducer
withHistory(boardReducer) returns a new reducer. It handles undo and
redo itself, and passes every other action through to the board reducer. The
board reducer doesn't know history exists, and its tests from the last lesson
still apply unchanged:
export function withHistory ( reducer ) {
return function historyReducer ( history , action ) {
const { past , present , future } = history ;
switch ( action . type ) {
case "undo" :
if ( past . length === 0 ) return history ;
return { past : past . slice ( 0 , - 1 ), present : past . at ( - 1 ), future : [ present , ... future ] };
case "redo" :
if ( future . length === 0 ) return history ;
return { past : [ ... past , present ], present : future [ 0 ], future : future . slice ( 1 ) };
default : {
const next = reducer ( present , action );
if ( next === present ) return history ;
return { past : [ ... past , present ], present : next , future : [] };
}
}
};
}
if (next === present) return history; matters too. An action that changes
nothing shouldn't add an undo step.
The initializer function
const [ history , dispatch ] = useReducer ( reducer , starterCards , createHistory );
The third argument is an initializer . React calls createHistory(starterCards)
once, on the first render, to build the starting state. It's the reducer
equivalent of useState(() => ...) from React Beginner Day 7: work done only
once, not on every render.
Predict
Move Read about reducers to Doing , press Undo , then add a new card.
Is Redo enabled?
Check your prediction No. Adding a card is a new change, so future is cleared. Redo would otherwise
bring back a state that never included your new card.
Exercise Limit the history Keep at most 10 steps in past, so a long session doesn't hold every state
forever. Change only history.js.
Your working space React · 8 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 { createHistory, withHistory } from "./history.js";
import { starterCards } from "./data.js";
const reducer = withHistory(boardReducer);
export default function App() {
const [history, dispatch] = useReducer(reducer, starterCards, createHistory);
const cards = history.present;
return (
<main>
<h1>Study Board</h1>
<div className="toolbar">
<button onClick={() => dispatch({ type: "undo" })} disabled={history.past.length === 0}>Undo</button>
<button onClick={() => dispatch({ type: "redo" })} disabled={history.future.length === 0}>Redo</button>
</div>
<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 },
];
// Wraps any reducer so its state can be undone and redone.
export function createHistory(present) {
return { past: [], present, future: [] };
}
export function withHistory(reducer) {
return function historyReducer(history, action) {
const { past, present, future } = history;
switch (action.type) {
case "undo":
if (past.length === 0) return history;
return { past: past.slice(0, -1), present: past.at(-1), future: [present, ...future] };
case "redo":
if (future.length === 0) return history;
return { past: [...past, present], present: future[0], future: future.slice(1) };
default: {
const next = reducer(present, action);
if (next === present) return history;
return { past: [...past, present], present: next, future: [] };
}
}
};
}
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;
}
Hint 1: the idea A history limit controls memory by discarding the oldest snapshots, while keeping the newest steps available to undo.
Hint 2: a first step Find the one place where past grows: the default branch, which builds a
new past from the old one plus present. That new array is what needs
trimming, from the front, so the oldest step goes first. Check it by adding
12 cards and then pressing Undo until it greys out: you should get 10
undos, not 12. Which array method returns the last few items without changing
the original?
Show one solution default : {
const next = reducer ( present , action );
if ( next === present ) return history;
return { past : [ ... past , present ]. slice ( - 10 ), present : next , future : [] };
} Mark as done Completion is saved in this browser only. It does not measure mastery.