Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 41 ยท Patterns and Performance

Undo/Redo and Persisting State

Build undo and redo with a higher-order reducer, then persist and rehydrate Redux state safely with versioning and migrations. Runnable examples included.

Two features that look hard in other architectures are almost free in Redux: undo/redo and saving state across page loads. Both follow from the same facts: state is a plain value, updated only by a reducer, and every old state is still a valid, complete state.

Undo and redo with a higher-order reducer

A higher-order reducer takes a reducer and returns a new reducer with extra behaviour. For history, we wrap the state in { past, present, future }:

  • On a normal action: push present onto past, compute the new present, clear future.
  • On undo: move the last of past into present, and put the old present onto the front of future.
  • On redo: the opposite.
flowchart LR
  P["past: [s1, s2]"] --> N["present: s3"]
  N --> F["future: []"]
  N -. "undo" .-> N2["present: s2<br/>past: [s1]<br/>future: [s3]"]

Undo moves the present into the future; redo brings it back.

JS A withHistory higher-order reducer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details worth noticing: an action that does not change the state (next === present) creates no history entry, and a new action after an undo clears future, as in every editor you use.

The idea scales: redux-undo is a library built on exactly this pattern, with options for filtering actions and grouping several actions into one undo step. In Redux Toolkit you would wrap the slice reducer: reducer: { drawing: withHistory(drawingSlice.reducer) }, and read state.drawing.present.

Cautions: history stores whole state references (cheap thanks to structural sharing, see Immer), but large states plus a big limit use memory; do not put server-owned data in undoable state, because undoing a local change would not undo what the server did.

Persisting state

Users expect a cart, theme or draft to survive a reload. The mechanism is: save a serializable part of the state when it changes, and rehydrate it as the preloadedState of the store when the app starts.

JavaScript
// Real Redux Toolkit code (read-only)
function loadState() {
  try {
    const raw = localStorage.getItem('app-state');
    return raw ? JSON.parse(raw) : undefined;   // undefined -> reducers' initial state
  } catch {
    return undefined;                           // blocked storage, bad JSON
  }
}

const store = configureStore({ reducer, preloadedState: loadState() });

store.subscribe(throttle(() => {
  const { cart, settings } = store.getState();  // save only what should persist
  try { localStorage.setItem('app-state', JSON.stringify({ cart, settings })); } catch {}
}, 500));

Persist only the slices that make sense: a cart yes, a loading flag or an auth token (use a secure cookie instead) no. Always wrap storage calls in try/catch: storage can be disabled, full or corrupted.

The preview sandbox on this site has no localStorage, so the next example uses an in-memory stand-in with the same getItem/setItem API.

Versioning and migrations

The hardest part is not saving, it is loading old saved data after you changed the state shape. A user who saved { cart: [ids] } last month opens the new version that expects { cart: { items: [...] } }. Without a plan, the app crashes for returning users only, which is hard to test.

The fix is to store a version number next to the data and run migrations from the saved version up to the current one.

JS Versioned persistence with migrations

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Redux Toolkit has no built-in persistence, but the popular redux-persist library implements the same idea (version, migrate, whitelist, and PersistGate to delay rendering until rehydration finishes). If you use it, you must tell the serializability check to ignore its action types.

Other persistence targets

  • Server: debounce a listener (see listeners) that PUTs the draft to an API.
  • IndexedDB: for large data (documents, offline caches), use an async store through a listener or thunk.
  • URL: filters and pagination belong in the URL so links can be shared; sync with the router and treat the URL as the source of truth.
  • Server-side rendering: serialize store.getState() into the HTML and pass it as preloadedState on the client, escaping < so the JSON cannot break out of the script tag.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a higher-order reducer return?

    withHistory takes a reducer and returns a new reducer.
  2. 2. After undo, a new normal action is dispatched. What happens to the future list?

    A new branch of history invalidates the redo stack.
  3. 3. Why store a version number with persisted state?

    Returning users may have data in an old shape.
  4. 4. Which should you NOT persist in localStorage?

    localStorage is readable by any script on the page; use secure HttpOnly cookies for auth.

Summary

  • Undo/redo is a higher-order reducer holding past, present and future.
  • Ignore actions that change nothing; clear future on new changes.
  • Persist selected, serializable slices and rehydrate through preloadedState.
  • Always guard storage with try/catch and handle corrupted data.
  • Version persisted state and write migrations for every shape change.

Next: Testing Redux logic