Skip to content

Instantly share code, notes, and snippets.

@izniburak
Created March 13, 2020 20:23
Show Gist options
  • Save izniburak/9b7564eaa92065e3f95b71fb9c104886 to your computer and use it in GitHub Desktop.
Save izniburak/9b7564eaa92065e3f95b71fb9c104886 to your computer and use it in GitHub Desktop.
import { useState, useLayoutEffect } from 'react'
const useLocalStorage = (key, defaultValue = null, prefix = 'store') => {
const storeKey = `${prefix}-${key}`
const [value, setValue] = useState(() => {
const data = localStorage.getItem(storeKey)
return data === null ? defaultValue : JSON.parse(data)
})
const updateValue = newValue => {
setValue(() => {
localStorage.setItem(storeKey, JSON.stringify(newValue))
return newValue
})
}
useLayoutEffect(() => {
const storageListener = e => {
if (e.storageArea === localStorage && e.key === storeKey) {
setValue(e.newValue === null ? defaultValue : JSON.parse(e.newValue))
}
}
window.addEventListener('storage', storageListener)
return () => window.removeEventListener('storage', storageListener)
})
return [value, updateValue]
}
export default useLocalStorage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment