Skip to content

Instantly share code, notes, and snippets.

@scsskid
Created October 27, 2020 14:26
Show Gist options
  • Save scsskid/2fdc31b9e6fa8f0874d6ed07a7e3f09c to your computer and use it in GitHub Desktop.
Save scsskid/2fdc31b9e6fa8f0874d6ed07a7e3f09c to your computer and use it in GitHub Desktop.
[useLocalStorageState] #react
function useLocalStorageState(
key,
defaultValue = '',
{ serialize = JSON.stringify, deserialize = JSON.parse } = {}
) {
const [state, setState] = React.useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key);
if (valueInLocalStorage) {
return deserialize(valueInLocalStorage);
}
return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
});
const prevKeyRef = React.useRef(key);
React.useEffect(() => {
const prevKey = prevKeyRef.current;
if (prevKey !== key) {
window.localStorage.removeItem(prevKey);
}
prevKeyRef.current = key;
window.localStorage.setItem(key, serialize(state));
}, [key, state, serialize]);
return [state, setState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment