Appearance
useStateDebouncedHistory
Shorthand for useStateHistory with debounced filter.
Demo
Usage
This function takes a snapshot of your counter after 1000ms when the value of it starts to change.
tsx
import { useStateDebouncedHistory } from '@reause/core'
import { useState } from 'react'
const [count, setCount] = useState(0)
const { history, undo, redo, canUndo, canRedo } = useStateDebouncedHistory([count, setCount], { debounce: 1000 })
setCount(1)
// committed once 1000ms pass without further changes
setCount(2)
// every change resets the window — only the last change inside it is recorded
console.log(history)
/* [
{ snapshot: 2, timestamp: 1601912898062 },
{ snapshot: 0, timestamp: 1601912898061 }
] */
undo() // count back to the previous recordThe source is the controlled [state, setState] tuple of an existing useState; commits are driven by an effect on state changes (upstream: useWatchIgnorable).
Type Declarations
Toggle
ts
export interface UseStateDebouncedHistoryOptions<Raw, Serialized = Raw> {
capacity?: number;
clone?: boolean | ((value: Raw) => Raw);
dump?: (value: Raw) => Serialized;
parse?: (value: Serialized) => Raw;
debounce?: number;
}
export interface UseStateDebouncedHistoryControls<Raw, Serialized = Raw> {
source: Raw;
last: UseRefHistoryRecord<Serialized>;
undoStack: UseRefHistoryRecord<Serialized>[];
redoStack: UseRefHistoryRecord<Serialized>[];
canUndo: boolean;
canRedo: boolean;
isTracking: boolean;
setSource: Dispatch<SetStateAction<Raw>>;
commit: () => void;
clear: () => void;
reset: () => void;
pause: () => void;
resume: (commitNow?: boolean) => void;
batch: (fn: (cancel: () => void) => void) => void;
}
export interface UseStateDebouncedHistoryReturn<Raw, Serialized = Raw> extends UseStateDebouncedHistoryControls<Raw, Serialized> {
history: UseRefHistoryRecord<Serialized>[];
undo: () => void;
redo: () => void;
}
export interface UseRefHistoryRecord<T> {
snapshot: T;
timestamp: number;
}
export interface UseStateManualHistoryControls<Raw, Serialized = Raw> {
source: Raw;
last: UseRefHistoryRecord<Serialized>;
undoStack: UseRefHistoryRecord<Serialized>[];
redoStack: UseRefHistoryRecord<Serialized>[];
canUndo: boolean;
canRedo: boolean;
undo: () => void;
redo: () => void;
clear: () => void;
reset: () => void;
setSource: Dispatch<SetStateAction<Raw>>;
}
export interface UseStateManualHistoryReturn<Raw, Serialized = Raw> extends UseStateManualHistoryControls<Raw, Serialized> {
history: UseRefHistoryRecord<Serialized>[];
commit: () => void;
}
export function useStateDebouncedHistory<Raw, Serialized = Raw>(state: State<Raw>, options?: UseStateDebouncedHistoryOptions<Raw, Serialized>): UseStateDebouncedHistoryReturn<Raw, Serialized>