Skip to content

React API

A React hook that wraps the core timeTravel instance and provides a reactive state property that triggers re-renders.

import { useTimeTravel } from "@biswaviraj/time-travel/react";
const { state, add, undo, redo, canUndo, canRedo } = useTimeTravel(0);

See the Getting Started page for a full component example, or the Examples page for more patterns.

ParameterTypeDescription
initialValueTThe initial state value
options.limitnumberMax past/future states to keep (default: 10)

UseTimeTravel<T> — all core API methods and properties, plus:

PropertyTypeDescription
stateTReactive current value — triggers re-render on change

The hook uses useSyncExternalStore under the hood, so it’s compatible with concurrent features and server-side rendering.

type FormData = { name: string; email: string };
function Form() {
const { state, add, undo, canUndo } = useTimeTravel<FormData>({
name: "",
email: "",
});
const update = (field: keyof FormData, value: string) => {
add({ ...state, [field]: value });
};
return (
<form>
<input
value={state.name}
onChange={(e) => update("name", e.target.value)}
/>
<input
value={state.email}
onChange={(e) => update("email", e.target.value)}
/>
<button type="button" onClick={() => undo()} disabled={!canUndo}>
Undo
</button>
</form>
);
}
const { state, add } = useTimeTravel(0, { limit: 50 });
type UseTimeTravel<T> = TimeTravel<T> & {
readonly state: T;
};