Home > database >  Listen localStorage in react(useEffect)
Listen localStorage in react(useEffect)

Time:01-13

I am using some third-party libraries in react. That will make some local storage change on the page. I tried to listen to that local storage change using javascript storage event and give localStorage.getItem('test') as the dependency of useEffect. But it is not listening to the localStorage change.

Here is my code

useEffect(() => {
  window.addEventListener('storage', () => {
    console.log(JSON.parse(localStorage.getItem('test')));
  })
},[])

How to listen the localStorage event in react.

CodePudding user response:

Based on this answer See the example on codesandbox

CodePudding user response:

You can this way!

useEffect(() => {
  function checkLocalData() {
    const item = localStorage.getItem('test')

    if (item) {
      checkLocalData(item)
    }
  }

  window.addEventListener('storage', checkLocalData)

  return () => {
    window.removeEventListener('storage', checkLocalData)
  }
}, [])
  • Related