fn

useRefHistory

v0.0.14testeddemo

Track the change history of a ref with undo/redo, pause/resume, batching, and manual commits.

Examples

ts
const count = ref(0);
const { history, undo, redo, canUndo, canRedo } = useRefHistory(count);

count.value = 1;
count.value = 2;
undo(); // count.value === 1
redo(); // count.value === 2
ts
// Deep tracking with bounded capacity and a custom serializer
const state = ref({ items: [] });
const { history } = useRefHistory(state, { deep: true, capacity: 10 });

Demo

Loading demo…

Signature

ts
export function useRefHistory<Raw, Serialized = Raw>(
  source: Ref<Raw>,
  options: UseRefHistoryOptions<Raw, Serialized> ={ ... }

Type Parameters

Raw
Serialized= Raw

Parameters

ParameterTypeDescription
sourceRef<Raw>The ref whose changes are tracked
options?UseRefHistoryOptions<Raw, Serialized>Tracking options (deep, flush, capacity, clone, dump, parse, eventFilter, shouldCommit)

Returns

UseRefHistoryReturn<Raw, Serialized>History records plus undo/redo/commit/reset/clear/pause/resume/batch/dispose
PropertyTypeDescription
historyRef<Array<UseRefHistoryRecord<Serialized>>>Bidirectional list of recorded snapshots, newest first
lastRef<UseRefHistoryRecord<Serialized>>The most recent snapshot record
undoStackRef<Array<UseRefHistoryRecord<Serialized>>>Undo history records (the redo stack), newest first
redoStackRef<Array<UseRefHistoryRecord<Serialized>>>Redo history records, newest first
isTrackingRef<boolean>Whether change tracking is currently active
canUndoComputedRef<boolean>Whether an undo operation is available
canRedoComputedRef<boolean>Whether a redo operation is available
undo() => voidStep the source back to the previous snapshot
redo() => voidStep the source forward to the next snapshot
clear() => voidClear all recorded history (keeps the current value as the only record)
commit() => voidManually record the current value as a new snapshot
reset() => voidReset the source back to the most recent snapshot, discarding uncommitted changes
pause() => voidPause change tracking
resume(commit?: boolean) => voidResume change tracking
batch(fn: (cancel: () => void) => void) => voidRun a function with tracking suspended, committing once on completion. Call the provided cancel to skip the trailing commit.
dispose() => voidStop the underlying watcher and clear all history