Last active
November 17, 2022 07:46
-
-
Save cyco130/b86ddb26e8f0ca4a9649d54ea507426e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { 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