Published
- 1 min read
reactive localstorage in react
The solution for this is noted below
reactive localstorage in react
Solution
function useStorageWatcher(key) {
const [val, setVal] = useState(localStorage.get(key))
useEffect(() => {
const handler = () => val !== localStorage.get(key) && setVal(localStorage.get(key))
window.addEventListener('storage', handle)
;() => window.removeEventListener('storage', handler)
}, [])
useEffect(() => {
setVal(localStorage.get(key))
}, [key])
return val
}
Try other methods by searching on the site. That is if this doesn’t work