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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Modeling history as past/present/future stacks makes undo and redo symmetric list operations.
  2. 2Returning the same state object on a no-op lets React skip re-renders cheaply.
  3. 3Wrapping a reducer in a custom hook hides the dispatch plumbing behind a clean, intention-revealing API.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Undo/redo form state with a React reducer — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code