Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda