Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Last active July 9, 2021 02:42
Show Gist options
  • Save gaurangrshah/5481620cd9b481683c7d019596db4e9d to your computer and use it in GitHub Desktop.
Save gaurangrshah/5481620cd9b481683c7d019596db4e9d to your computer and use it in GitHub Desktop.
function useLocalStorageState(
key,
defaultValue = '',
// the = {} fixes the error we would get from destructuring when no argument was passed
// Check https://jacobparis.com/blog/destructure-arguments for a detailed explanation
{serialize = JSON.stringify, deserialize = JSON.parse} = {},
) {
const [state, setState] = React.useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key)
if (valueInLocalStorage) {
// the try/catch is here in case the localStorage value was set before
// we had the serialization in place (like we do in previous extra credits)
try {
return deserialize(valueInLocalStorage)
} catch (error) {
window.localStorage.removeItem(key)
}
}
return typeof defaultValue === 'function' ? defaultValue() : defaultValue
})
const prevKeyRef = React.useRef(key)
// Check the example at src/examples/local-state-key-change.js to visualize a key change
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]
}
/*
USAGE:
const [name, setName] = useLocalStorageState('name', 'bob'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment