Skip to content

Instantly share code, notes, and snippets.

@revskill10
Forked from augustolazaro/useLocalStorage.ts
Created April 13, 2023 13:16
Show Gist options
  • Save revskill10/2ea89259943ea8460912cdacd4a48865 to your computer and use it in GitHub Desktop.
Save revskill10/2ea89259943ea8460912cdacd4a48865 to your computer and use it in GitHub Desktop.
React hook to manage local storage changes
import * as React from 'react'
const originalSetItem = localStorage.setItem
localStorage.setItem = function() {
const event = new Event('storageChange')
document.dispatchEvent(event)
originalSetItem.apply(this, arguments)
}
const originalRemoveItem = localStorage.removeItem
localStorage.removeItem = function() {
const event = new Event('storageChange')
document.dispatchEvent(event)
originalRemoveItem.apply(this, arguments)
}
function useLocalStorage(key: string) {
const storageItem = localStorage.getItem(key)
const [storedValue, setValue] = React.useState(
!!storageItem ? JSON.parse(storageItem) : null
)
const setLocalItem = () => {
/** local storage update is not that fast */
/** it makes sure that we are getting the new value */
setTimeout(() => {
const itemValueFromStorage = localStorage.getItem(key)
const value = itemValueFromStorage && JSON.parse(itemValueFromStorage)
setValue(value)
}, 50)
}
const setStoredValue = (value: string | object) => {
const parsedValue = typeof value === 'object' ? JSON.stringify(value) : value
localStorage.setItem(key, parsedValue)
}
React.useEffect(() => {
document.addEventListener(
'storageChange',
setLocalItem,
false
)
return () => document.removeEventListener('storageChange', setLocalItem)
}, [])
return { storedValue, setStoredValue }
}
export default useLocalStorage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment