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

128
Vistas
React useEffects with setData is not getting into an infinite loop?

const [resourceType, setResourceType] = useState("posts");
const [data, setData] = useState("");
useEffect(() => {
   console.log("use effects called: " + resourceType);
   fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
     .then((result) => {
         return result.json().then((data) => {
             return {
                 data: data,
                 response: result.status,
             };
         });
         //JSON.parse(result);
     })
     .then((data) => {
         console.log("here");
         setData(JSON.stringify(data));
         console.log(data);
     });
});   
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I have the above code that is fetching dummy data from JSON placeholder URL and then updating the data variable (setData(JSON.stringify(data))). My question is, this implementation should go into an infinite loop as per my understanding of useEffect and useState react hook. Here is what I think should happen, the page renders it calls useEffect it updates data variable which will cause re-render of the component which should again call useEffect hence re-rending the component and the cycle goes on. But this is not happening and the useEffect is called only twice. Why is this happening?

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

The data is the same the second time you call setData, so:

  • react doesn’t re-render your component, so
  • the effect doesn’t run, hence
  • no infinite loop.

You’d probably see an infinite loop if you weren’t stringifying the data.

about 4 years ago · Santiago Gelvez Denunciar

0

You need to pass the data object as the dependency array to useEffect()

useEffect(() => {
   ...your code
}, [data]);
about 4 years ago · Santiago Gelvez 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