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

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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