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

169
Visualizações
Why does setState in the body of the component cause an infinite loop even if it's setting the same initial value?

The code below should not trigger a re-render because it's passing the same initial value right? But it instead causes 'Too many re-renders' error.

function Test() {
   const [counter, setCounter] = useState(0)
   setCounter(0)
   return <></>
}

Edit: If you setCounter(0) in a function and attach it to a button click, it won't trigger a re-render since it has the same value so why does it trigger re-render when placed in the body of the component? I am aware of the useEffect with empty dependency array to avoid the infinite loop.

If you do this, you'll see that it doesn't re-render:

function Test() {
   const [counter, setCounter] = useState(0)

   console.log('render');

   const set = () => {
     setCounter(0)
   };

   return <button onClick={set}>Set</button>
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In React, It does not Matter You are Updating Same Value or Not. If you Update the State It Will rerender the Component..

In your case , You Have SetState in the body of the Component.. So it will rerender and Cause an Infinite Loop..

If you Just want to Update Once, use useEffect instead.

useEffect(() => {
 setCounter(0)
},[])
about 4 years ago · Juan Pablo Isaza Relatório

0

If you update the state directly inside your render method or a body of a functional component, it will cause an infinite loop.

State updates → triggers re-render → state updates → triggers re-render → …

You can have look at this article

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