Last active
September 22, 2020 04:50
-
-
Save JohanAltamar/6be4656a3b1eea0755ed9b43af8c4108 to your computer and use it in GitHub Desktop.
Persist react hooks state at LocalStorage
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 { useEffect, useState } from 'react'; | |
export function usePersistedState(key, defaultValue) { | |
const [state, setState] = useState( | |
() => JSON.parse(localStorage.getItem(key)) || defaultValue | |
); | |
useEffect(() => { | |
localStorage.setItem(key, JSON.stringify(state)); | |
}, [key, state]); | |
return [state, setState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment