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

238
Vistas
why does useEffect run once the window.innerWidth changes even though the second param in it is an empty array

useEffect in this code runs every time the window size changes, but the second parameter in useEffect is an empty array, I thought as long as the second parameter doesn't change compare to last time, the useEffect won't run

import React from "react"

export default function WindowTracker() {
    
    const [windowWidth, setWindowWidth] = React.useState(window.innerWidth)
    
    React.useEffect(() => {
        window.addEventListener("resize", function() {
            setWindowWidth(window.innerWidth)
        })
    }, [])
    
    return (
        <h1>Window width: {windowWidth}</h1>
    )
}

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

0

It is not that useEffect runs, rather the registered event listener callback. useEffect indeed runs once and registers the event listener once. But then afterwards, the listener callback is called.

You told the event listener to listen to resize right? So you should expect it to be called any time resize happens.

Also if you return function from your effect, it will run when component unmounts (because of empty dependencies); you can use that to remove listener:

React.useEffect(() => {
  let cb = function () {
    setWindowWidth(window.innerWidth);
  };
  window.addEventListener("resize", cb);

  return () => {
    window.removeEventListener("resize", cb);
  };
}, []);
about 4 years ago · Juan Pablo Isaza Denunciar

0

If you console.log inside of useEffect, you will see it will actually gets run only once. Basically you have set once the event listener for the resize event. But you still have the registered event listener in place, which works as it's supposed to.

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