Created
June 24, 2021 10:58
-
-
Save codemile/adc94676d6a2d91e09b3959b2b145f07 to your computer and use it in GitHub Desktop.
A hook that persists useState() to localStorage.
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 {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