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

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

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 Denunciar

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