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

172
Visualizações
For loop in useEffect too many re-renders

I am working on a for loop that starts with 1 column at the window.innerHeight of 530px and increments with +1 if the window.innerHeight gets incremented with 40.

This is what I have right now, but it says too many re-renders everytime. Does anyone know why?

let gridcolumns = 1;
  useEffect(() => {
    for (let i = 530; i < window.innerHeight; i += 40) {
      gridcolumns += 1;
    }
  });
  setColumnsAmount(gridcolumns);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to add dependency list to your useEffect :

let gridcolumns = 1;
  useEffect(() => {
    for (let i = 530; i < window.innerHeight; i += 40) {
      gridcolumns += 1;
    }
  setColumnsAmount(gridcolumns);
  },[]);
about 4 years ago · Juan Pablo Isaza Relatório

0

Your useEffect call has no dependency array, so its callback is called after every render. The callback then does setColumnsAmount, which triggers a re-render, which triggers the useEffect callback, which triggers a re-render, etc.

You need to specify a dependency array that says what it is that needs to change to make you want to run the callback, or don't use useEffect for this at all and do the columnsAmount change in an event callback (perhaps a resize event).


Side note: You can probably replace the for loop with const x = Math.floor(window.innerHeight / 40); and then doing whatever it is you want to with x (for instance, you could add it to gridColumns if that's really the right thing).

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