@modern-kit/react
Version:
49 lines (45 loc) • 1.55 kB
JavaScript
;
var utils = require('@modern-kit/utils');
var React = require('react');
function useStateWithHistory(initialValue, capacity = 10) {
const initialValueToUse = utils.isFunction(initialValue) ? initialValue() : initialValue;
const [state, innerSetState] = React.useState(initialValueToUse);
const history = React.useRef([initialValueToUse]);
const pointer = React.useRef(0);
const setState = React.useCallback(
(newState) => {
const newStateToUse = utils.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 = React.useCallback(() => {
if (pointer.current < 1) {
return;
}
pointer.current--;
innerSetState(history.current[pointer.current]);
}, []);
const forward = React.useCallback(() => {
if (pointer.current >= history.current.length - 1) {
return;
}
pointer.current++;
innerSetState(history.current[pointer.current]);
}, []);
const goToIndex = React.useCallback((index) => {
if (utils.at(history.current, index) == null) {
return;
}
pointer.current = index;
innerSetState(utils.at(history.current, pointer.current));
}, []);
return { state, setState, forward, back, goToIndex };
}
exports.useStateWithHistory = useStateWithHistory;
//# sourceMappingURL=index.cjs.map