@utilityjs/use-memento-state
v1.0.1
Published
A React hook that keeps the track of the history of the state changes.
Downloads
9
Maintainers
Readme
A React hook that keeps the track of the history of the state changes.
npm i @utilityjs/use-memento-state | yarn add @utilityjs/use-memento-state
Usage
const MementoDemo = () => {
const {
state,
setState,
pastStates,
futureStates,
redo,
undo,
reset
} = useMementoState(0);
return (
<React.Fragment>
<button onClick={() => void setState(v => v + 1)}>Increase</button>
<button onClick={() => void undo()}>Undo</button>
<button onClick={() => void redo()}>Redo</button>
<button onClick={() => void reset()}>Reset</button>
<hr />
<strong>History</strong>
<ul>
{pastStates.map(past => (
<li style={{ color: "red" }} key={past}>
{past}
</li>
))}
<li style={{ color: "#000", fontWeight: "bold" }}>
{state}{" "}
<span role="img" aria-label="Arrow">
⬅️
</span>
</li>
{futureStates.map(future => (
<li style={{ color: "green" }} key={future}>
{future}
</li>
))}
</ul>
</React.Fragment>
);
};
API
useMementoState(initialPresent)
interface Mementos<T> {
state: T;
pastStates: T[];
futureStates: T[];
setState: React.Dispatch<React.SetStateAction<T>>;
undo: () => void;
redo: () => void;
reset: () => void;
hasPastState: () => boolean;
hasFutureState: () => boolean;
}
declare const useMementoState: <T>(initialPresent: T) => Mementos<T>;
initialPresent
The value of the initial present state.