Skip to content

Instantly share code, notes, and snippets.

@cyco130
Last active November 17, 2022 07:46
Show Gist options
  • Save cyco130/b86ddb26e8f0ca4a9649d54ea507426e to your computer and use it in GitHub Desktop.
Save cyco130/b86ddb26e8f0ca4a9649d54ea507426e to your computer and use it in GitHub Desktop.
import { Dispatch, SetStateAction, useState, useEffect } from 'react';
export function usePersistentState<T>(
key: string,
defaultValue: T
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState<T>(defaultValue);
// Save to session storage on unload
useEffect(() => {
function handleBeforeUnload() {
sessionStorage.setItem(key, JSON.stringify(state));
}
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [key, state]);
// Restore from session storage on mount
useEffect(() => {
const value = sessionStorage.getItem(key);
if (value) {
setState(JSON.parse(value));
sessionStorage.removeItem(key);
}
}, [key]);
return [state, setState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment