Skip to content

Instantly share code, notes, and snippets.

@Infi-Knight
Created October 31, 2020 09:22
Show Gist options
  • Select an option

  • Save Infi-Knight/54aaec6fb0cfcae1c4919b55a4dfe34e to your computer and use it in GitHub Desktop.

Select an option

Save Infi-Knight/54aaec6fb0cfcae1c4919b55a4dfe34e to your computer and use it in GitHub Desktop.
React hook to sync component state with local storage
import React, {useState, useRef, useEffect} from 'react'
export const useLocalStorageState = (
key,
defaultValue = '',
{serialize = JSON.stringify, deserialize = JSON.parse} = {}
) => {
const [state, setState] = useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key)
if (valueInLocalStorage){
return deserialize(valueInLocalStorage)
}
return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
})
const prevKeyRef = useRef(key)
useEffect(() => {
const prevKey = prevKeyRef.current
if (prevKey !== key) {
window.localStorage.removeItem(key)
}
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