Created
October 27, 2020 14:26
-
-
Save scsskid/2fdc31b9e6fa8f0874d6ed07a7e3f09c to your computer and use it in GitHub Desktop.
[useLocalStorageState] #react
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
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