UNPKG

@modern-kit/react

Version:
47 lines (44 loc) 1.48 kB
import { isFunction, at } from '@modern-kit/utils'; import { useState, useRef, useCallback } from 'react'; function useStateWithHistory(initialValue, capacity = 10) { const initialValueToUse = isFunction(initialValue) ? initialValue() : initialValue; const [state, innerSetState] = useState(initialValueToUse); const history = useRef([initialValueToUse]); const pointer = useRef(0); const setState = useCallback( (newState) => { const newStateToUse = isFunction(newState) ? newState(state) : newState; if (history.current.length === capacity) { history.current.shift(); } history.current.push(newStateToUse); pointer.current = history.current.length - 1; innerSetState(newStateToUse); }, [capacity, state] ); const back = useCallback(() => { if (pointer.current < 1) { return; } pointer.current--; innerSetState(history.current[pointer.current]); }, []); const forward = useCallback(() => { if (pointer.current >= history.current.length - 1) { return; } pointer.current++; innerSetState(history.current[pointer.current]); }, []); const goToIndex = useCallback((index) => { if (at(history.current, index) == null) { return; } pointer.current = index; innerSetState(at(history.current, pointer.current)); }, []); return { state, setState, forward, back, goToIndex }; } export { useStateWithHistory }; //# sourceMappingURL=index.mjs.map