Skip to content

Instantly share code, notes, and snippets.

@sskirby
Created November 11, 2021 17:32
Show Gist options
  • Save sskirby/49bb0462f98a53ad20980ef509871c22 to your computer and use it in GitHub Desktop.
Save sskirby/49bb0462f98a53ad20980ef509871c22 to your computer and use it in GitHub Desktop.
React hook for state persisted to local storage
import * as React from 'react'
/**
*
* @param {String} key The key to set in localStorage for this value
* @param {Object} defaultValue The value to use if it is not already in localStorage
* @param {{serialize: Function, deserialize: Function}} options The serialize and deserialize functions to use (defaults to JSON.stringify and JSON.parse respectively)
*/
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]
}
export {useLocalStorageState}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment