Skip to content

Instantly share code, notes, and snippets.

@codemile
Created June 24, 2021 10:58
Show Gist options
  • Save codemile/adc94676d6a2d91e09b3959b2b145f07 to your computer and use it in GitHub Desktop.
Save codemile/adc94676d6a2d91e09b3959b2b145f07 to your computer and use it in GitHub Desktop.
A hook that persists useState() to localStorage.
import {useCallback, useEffect, useState} from 'react';
export const useStateStorage = <TType extends any>(
key: string,
defaultValue: TType
) => {
const [value, setState] = useState(defaultValue);
useEffect(() => {
const store = localStorage.getItem(key);
if (store != null) {
try {
setState(JSON.parse(store) as TType);
} catch (err) {
localStorage.removeItem(key);
}
}
}, [key]);
const setValue = useCallback(
(newValue: TType) => {
setState(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
},
[key]
);
return [value, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment