Skip to content

Instantly share code, notes, and snippets.

@stephanedupont
Created January 21, 2023 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephanedupont/5da29a3f9542e346aa652d11ab18ce79 to your computer and use it in GitHub Desktop.
Save stephanedupont/5da29a3f9542e346aa652d11ab18ce79 to your computer and use it in GitHub Desktop.
History React Hook
import React, {useCallback} from "react";
export function useHistory<T>(state: T): [
pushState: (state: T) => void,
undo: () => T | null,
redo: () => T | null,
] {
const [history] = React.useState<{ data: Array<T>, index: number }>({data: [state], index: 1});
const pushState = useCallback((state: T) => {
if (history.index < history.data.length) {
history.data = history.data.slice(0, history.index);
}
history.data.push(state);
history.index++;
}, [history]);
const undo = useCallback(() => {
if (history.index <= 1) return null;
history.index--;
return history.data[history.index - 1];
}, [history]);
const redo = useCallback(() => {
if (history.index > (history.data.length - 1)) return null;
history.index++;
return history.data[history.index - 1];
}, [history]);
return [pushState, undo, redo];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment