Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!