-
-
Save ayse8888/06ed1b73efad11bbcbd7064e410d8198 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