mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
* feat: add useStateHistory hook; * fix: createBreakpoint lint fix (author skipped hooks);
1.8 KiB
1.8 KiB
useStateHistory
Stores defined amount of previous state values and provides handles to travel through them.
Usage
Reference
const [state, setState, stateHistory] = useStateWithHistory<S = undefined>(
initialState?: S | (()=>S),
historyCapacity?: number = 10,
initialHistory?: S
);
state,setStateandinitialStateare exactly the same with native React'suseStatehook;historyCapacity- amount of history entries that hold by storage;initialHistory- if defined it will be used as initial history value, otherwise history will equals[ initialState ].
Initial state will not be pushed to initial history.
If entries amount is greater thanhistoryCapacityparameter it wont be modified on init but will be trimmed on nextsetState;stateHistory- an object containing history state:history: S[]- an array holding history entries. I will have the same ref all the time so pe careful with that one!;position: number- current position index in history;capacity: number = 10- maximum amount of history entries;back: (amount?: number) => void- go back in state history, it will causesetStateinvoke and component re-render.
If first element of history reached, the call will have no effect;forward: (amount?: number) => void- go forward in state history, it will causesetStateinvoke and component re-render.
If last element of history reached, the call will have no effect;go: (position: number) => void- go to arbitrary position in history.
In casepositionis non-negative ot will count elements from beginning. Negativepositionwill cause elements counting from the end, sogo(-2)equalsgo(history.length - 1);