Created
January 21, 2023 11:51
-
-
Save stephanedupont/5da29a3f9542e346aa652d11ab18ce79 to your computer and use it in GitHub Desktop.
History React Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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