Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
How do i re-run useEffect hook if the localstorage value has been changed?

I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.

My useEffect looks like this :

useEffect(() => {
      //getting all localstorage items and setting to a variable
      const localStorageItems = { ...localStorage }

      // filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.
    
      const filteredByKey = Object.fromEntries(
        Object.entries(localStorageItems).filter(([key, value]) => {
          if (key.startsWith("http")) {
            testArr2.push({ urls: [key, value] })
            // setTestData({ urls: [key, value] })
            setTestData((prev) => [...prev, { key, value }])
          }
        })
      )
    }, [])

My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.

The Problem :

  • I cannot pass window.localstorage to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.

What I have tried:

  • I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)
  • I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.

Please help. Thanks for reading this far.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

i can give you a work around for this use case, create react context that syncs with localStorage. you can use the context as a useEffect dependency. sync means, take the value from localStorage at starting and update the context along with the localStorage from your app.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Define a state that holds the local storage value and pass it as a useEffect parameter.

const [localStorageData, setLocalStorageData] = useState([]);

useEffect(() => {

    // Your codes

}, [localStorageData])
about 4 years ago · Juan Pablo Isaza Denunciar

0

you can use 'storage' event listener

window.addEventListener('storage', function(e) {
  if (e.newValue) {
    console.log('new data is saved ...')
    // ...... your code
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda