javascript
62 lines · 10 steps
Undo/redo form state with a React reducer
A three-stack reducer gives any React form full undo and redo history behind a simple hook.
Explained by
highlit
1import { useReducer, useCallback } from 'react';
2
3function historyReducer(state, action) {
4 const { past, present, future } = state;
5
6 switch (action.type) {
7 case 'set': {
8 const next = typeof action.payload === 'function'
9 ? action.payload(present)
10 : { ...present, ...action.payload };
11 if (Object.is(next, present)) return state;
12 return { past: [...past, present], present: next, future: [] };
13 }
14 case 'undo': {
15 if (past.length === 0) return state;
16 const previous = past[past.length - 1];
17 return {
18 past: past.slice(0, -1),
19 present: previous,
20 future: [present, ...future],
21 };
22 }
23 case 'redo': {
24 if (future.length === 0) return state;
25 const [next, ...rest] = future;
26 return { past: [...past, present], present: next, future: rest };
27 }
28 case 'reset':
29 return { past: [], present: action.payload, future: [] };
30 default:
31 return state;
32 }
33}
34
35export function useFormHistory(initialValues) {
36 const [state, dispatch] = useReducer(historyReducer, {
37 past: [],
38 present: initialValues,
39 future: [],
40 });
41
42 const setField = useCallback((name, value) => {
43 dispatch({ type: 'set', payload: { [name]: value } });
44 }, []);
45
46 const undo = useCallback(() => dispatch({ type: 'undo' }), []);
47 const redo = useCallback(() => dispatch({ type: 'redo' }), []);
48 const reset = useCallback(
49 (values = initialValues) => dispatch({ type: 'reset', payload: values }),
50 [initialValues],
51 );
52
53 return {
54 values: state.present,
55 setField,
56 undo,
57 redo,
58 reset,
59 canUndo: state.past.length > 0,
60 canRedo: state.future.length > 0,
61 };
62}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modeling history as past/present/future stacks makes undo and redo symmetric list operations.
- 2Returning the same state object on a no-op lets React skip re-renders cheaply.
- 3Wrapping a reducer in a custom hook hides the dispatch plumbing behind a clean, intention-revealing API.
Related explainers
javascript
import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; function csvCell(value) {
Streaming a CSV export in a Next.js route
streaming
csv
readablestream
Advanced
9 steps
java
import java.util.HashSet; import java.util.Set; public final class CollectionDiff<T> {
Diffing two collections with set operations
set-operations
immutability
generics
Intermediate
8 steps
javascript
class MovingAverage { constructor(windowSize) { if (!Number.isInteger(windowSize) || windowSize <= 0) { throw new RangeError('windowSize must be a positive integer');
A rolling average over a fixed window
circular-buffer
streaming
async-generators
Intermediate
7 steps
java
public record AppConfig( String host, int port, String databaseUrl,
Loading typed config from env vars in Java
records
configuration
environment-variables
Intermediate
6 steps
javascript
const { Pool } = require('pg'); const pool = new Pool({ connectionString: process.env.DATABASE_URL,
Per-request Postgres connections in Express
connection-pooling
middleware
transactions
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); const db = require('../db');
Building a paginated orders page in Express
pagination
routing
sql-queries
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/undo-redo-form-state-with-a-react-reducer-explained-javascript-ae3b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.