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

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

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

0

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

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