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

128
Visualizações
useEffect goes in an infinite loop. How to fix this?

Please alter this code so that useEffect does not keep calling itself again and again. Here, I am fetching data from the backend and updating state within the useEffect, which itself is the dependency. Is there some easy way to fix it?

My use case: I use a form to add a post and once I submit the form, I want it to show the updated list of posts right away. 'Posts' is a component where the updated list of posts are passed as props and each individual post is rendered within component 'Post'. So, I want to pass the updated list of post to 'Posts' once the form is submitted

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink + '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, [posts])
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink + '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, []) // Change here
about 4 years ago · Juan Pablo Isaza Relatório

0

This is whats happening right now in your code.

useEffect fires when the "posts" value change. the useEffect changes the "posts" which triggers useEffect because useEffect changed "posts"

this is an infinite loop. remove [posts] from dependency and find a workaround.

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