Appearance
useStateThrottledHistory
Shorthand for useStateHistory with throttled filter.
Demo
Usage
This function takes the first snapshot right after the counter's value was changed and the second with a delay of 1000ms.
tsx
import { useStateThrottledHistory } from '@reause/core'
import { useState } from 'react'
const [count, setCount] = useState(0)
const { history, undo, redo, canUndo, canRedo } = useStateThrottledHistory([count, setCount], { throttle: 1000 })
setCount(1)
// first change after a quiet window commits immediately (leading edge)
setCount(2)
// changes inside the throttle window collapse into a single trailing commit
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 UseStateThrottledHistoryOptions<Raw, Serialized = Raw> {
capacity?: number;
clone?: boolean | ((value: Raw) => Raw);
dump?: (value: Raw) => Serialized;
parse?: (value: Serialized) => Raw;
throttle?: number;
trailing?: boolean;
}
export interface UseStateThrottledHistoryControls<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 UseStateThrottledHistoryReturn<Raw, Serialized = Raw> extends UseStateThrottledHistoryControls<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 useStateThrottledHistory<Raw, Serialized = Raw>(state: State<Raw>, options?: UseStateThrottledHistoryOptions<Raw, Serialized>): UseStateThrottledHistoryReturn<Raw, Serialized>