Skip to content

Instantly share code, notes, and snippets.

@nihlton
Created March 29, 2022 22:09
Show Gist options
  • Save nihlton/57c6db57a90c07c884e6f7a0bd2e24e3 to your computer and use it in GitHub Desktop.
Save nihlton/57c6db57a90c07c884e6f7a0bd2e24e3 to your computer and use it in GitHub Desktop.
state hook, with history methods (set/undo/redo)
import { useState } from 'react';
const useHistory = (initialState) => {
const [history, setHistory] = useState([initialState]);
const [historyPos, setHistoryPos] = useState(0);
const canUndo = historyPos;
const canRedo = historyPos !== history.length - 1;
const value = history[historyPos];
const undo = canUndo ? () => setHistoryPos((p) => p - 1) : null;
const redo = canRedo ? () => setHistoryPos((p) => p + 1) : null;
const set = (nVal) => {
const finalValue = typeof nVal === 'function' ? nVal(value) : nVal;
const newHistory = [...history.slice(0, historyPos + 1), finalValue];
setHistory(newHistory);
setHistoryPos(newHistory.length - 1);
};
return [value, set, undo, redo];
};
export default useHistory;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment