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

92
Visualizações
React component disappears in a blink when using useEffect()

When I use this the labs field only gets updated for a millisecond and is gone after that.

  // the pagination component
  const [state, setState] = useState({
    pageCount: 0,
    currentPage: 0,
    labs: [],
  });

  useEffect(() => {
    labPageCount()
      .then((res) => setState({ ...state, pageCount: res.data.pageCount }))
      .catch(console.log);
  }, [state.pageCount]);

  useEffect(() => {
    fetchLabs(state.currentPage)
      .then((res) => setState({ ...state, labs: res.data }))
      .catch(console.log);
  }, [state.currentPage]);

Now if I add labs to the array in the second useEffect(), then it results in an infinite loop:-

 useEffect(() => {
    fetchLabs(state.currentPage)
      .then((res) => setState({ ...state, labs: res.data }))
      .catch(console.log);
  }, [state.currentPage, state.labs]);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Inside the second snipped, you are changing the labs by calling setState, then you are watching the changes on state.labs which causes the hook to be run again.

Somehow you need to compare labs then if they are different you should setState.

Alternatively you can call fetchLabs where you change the labs instead of calling in useEffect hook.

about 4 years ago · Juan Pablo Isaza Relatório

0

state updates in react are asynchronous so if you are setting state multiple times at different places in code. then directly using the ...state variable to get the previous value might not work as expected.
Instead of setting a state like this -

setState({ ...state, pageCount: res.data.pageCount })

Try out this to get the previous value from the state -

setState((prevState) => ({ ...prevState, pageCount: res.data.pageCount }))

And you need not add state.labs in dependency array, it will going to cause infinite loop if you are changing value of dependency array inside same useEffect.

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