A React hook for state time travel with undo, redo, reset and archive functionalities.
A React hook for state time travel with undo, redo, reset and archive functionalities.
React hooks for Travels: patch-based undo/redo state with immutable updates, manual archiving, rebasing, and shared-store support.
use-travel is the React layer for travels. It keeps the same core model as Travels, which stores JSON Patch history instead of full state snapshots, but exposes that model through React-friendly hooks:
useTravel for component-scoped state with undo/redouseTravelStore for subscribing React components to an existing immutable Travels instanceUse plain travels directly when your state lives outside React, you need imperative reads right after navigation, or you need mutable: true.
useTravel, useTravelStore, and travelsdraft.count += 1 while keeping immutable React state.Travels store with useTravelStore.npm install use-travel travels mutative
# or
yarn add use-travel travels mutative
# or
pnpm add use-travel travels mutative| use-travel | travels |
|---|---|
2.2.x |
^2.2.0 |
2.1.x |
^2.1.0 |
2.0.x |
^2.0.0 |
1.8.1–1.9.0 |
^1.3.1 (persistence and metadata APIs) |
1.8.0 |
>= 1.2.0 (required for rebase support) |
({ count: 1 })) |
setState((draft) => { draft.count += 1 })useTravel, useTravelStore, and travelsuseTravel when the state belongs to a React component and React should own the lifecycle.useTravelStore when you already have a shared immutable Travels instance and want React to stay subscribed to it.travels when another layer is the source of truth, you need imperative getState() reads after back() or forward(), or you need mutable: true.useTravel(initialState, options?)Creates a component-scoped immutable Travels instance and returns a tuple:
const [state, setState, controls] = useTravel(initialState, options);useTravel always uses immutable mode internally so React can observe state changes through reference updates. mutable and the controlled-journal-only controlledApply option are intentionally not supported here.
| Option | Type | Description | Default |
|---|---|---|---|
maxHistory |
number |
Maximum number of history entries to keep | 10 |
history |
TravelsHistory |
Restore validated history returned by Travels.deserialize(...) |
undefined |
initialPatches |
TravelPatches |
Patch history to restore from persistence | { patches: [], inversePatches: [] } |
strictInitialPatches |
boolean |
Throw when persisted patches are invalid instead of falling back to empty history | false |
initialPosition |
number |
History position to restore from persistence | 0 |
autoArchive |
boolean |
Save each change automatically or require manual archive() |
true |
warnOnUnsupportedState |
boolean |
Warn in development about weak state, patch, metadata, or persistence semantics | development only |
onError |
(error) => void |
Receive wrapped Travels operation errors | undefined |
onBranchDiscard |
(event) => void |
Observe redo history discarded by a new edit | undefined |
onWarning |
(warning) => void |
Receive structured non-fatal Travels warnings | undefined |
onObserverError |
(event) => void |
Receive listener, devtools, and observer-hook failures | undefined |
devtools |
(event) => void |
Observe unified TravelsEvent timeline events |
undefined |
enableAutoFreeze |
boolean |
Forwarded to Mutative immutability options | false |
strict |
boolean |
Forwarded to Mutative strict immutability checks | false |
mark |
Mark[] |
Forwarded to Mutative mark options | () => void |
patchesOptions |
PatchesOptions |
Customize patch output such as { pathAsArray: true } |
enabled |
Common tuple members:
| Member | Type | Description |
|---|---|---|
state |
Value |
Current render snapshot |
setState |
Updater |
Updates state with a value, function, or draft mutation |
controls.position |
number |
Current position in the history timeline |
controls.getHistory() |
() => Value[] |
Returns the history as state snapshots |
controls.patches |
TravelPatches |
Returns the stored patch history |
controls.back(amount?) |
(amount?: number) => void |
Undo one or more steps |
controls.forward(amount?) |
(amount?: number) => void |
Redo one or more steps |
controls.go(position) |
(position: number) => void |
Jump to a specific history position |
controls.reset() |
() => void |
Reset to the initial state and clear history |
controls.rebase() |
() => void |
Make the current state the new baseline and discard past and future history |
controls.canBack() |
() => boolean |
Imperative predicate — whether undo is possible (use in event handlers) |
controls.canForward() |
() => boolean |
Imperative predicate — whether redo is possible (use in event handlers) |
controls.canUndo |
boolean |
Render-safe reactive flag — whether undo is possible (read during render) |
controls.canRedo |
boolean |
Render-safe reactive flag — whether redo is possible (read during render) |
When autoArchive: false, the controls also include:
| Member | Type | Description |
|---|---|---|
controls.archive() |
() => void |
Commit the current working state as the next undo step |
controls.canArchive() |
() => boolean |
Whether there are unarchived changes |
canUndo / canRedo are reactive getters and canBack() / canForward() are methods. They report the same thing, but are meant for different contexts:
disabled={!controls.canUndo}), use the canUndo / canRedo getters. They are re-read on every render, so they stay correct — including under the React Compiler, which memoises method calls on the stable controls reference and would otherwise freeze controls.canBack() at its first-render value.onClick={() => controls.canBack() && controls.back()}), the canBack() / canForward() methods are fine.The methods are kept for backward compatibility and imperative use; the getters are the render-safe form.
useTravelStore(travels)Subscribes React to an existing immutable Travels instance without creating a new store.
// store.ts
import { Travels } from 'travels';
export const travels = new Travels({ count: 0 });// Counter.tsx
import { useTravelStore } from 'use-travel';
import { travels } from './store';
export function Counter() {
const [state, setState, controls] = useTravelStore(travels);
return (
);
}Important notes for useTravelStore:
Travels instances. Passing a store created with mutable: true throws.useTravel, including rebase().state is still a render snapshot.travels.back() or travels.forward() and read travels.getState() directly from the store.use-travel supports two recording modes.
With the default autoArchive: true, every setState call becomes its own undo step.
const [state, setState, controls] = useTravel({ count: 0 });
function increment() {
setState((draft) => {
draft.count += 1;
});
}
// Three separate user interactions:
// click #1 -> count = 1
// click #2 -> count = 2
// click #3 -> count = 3
controls.back(); // { count: 2 }With autoArchive: false, you decide when the current working state should become a committed history entry.
This is useful for flows like forms, drag interactions, or multi-
No open issues yet, or sync has not completed.