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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 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.