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

103
Views
Two React useEffect functions affecting the same state

I have a certain piece of state that is updated via api calls. I have multiple components that affect this state and am running into an issue. Basically, the issue comes down to how the state is set because of the time it takes for the api call to finish.

Basically: Component 1 is loaded and the useEffect is triggered to update the state Component 2 is loaded right afterwards and also has a useEffect making the same api call for different data

If the api call in Component 1 takes longer than Component 2, Component 2's set state is then overwritten by the set state of Component 1 once its api call finishes, even if Component 1 is no longer mounted.

Is there a way in functional components to cancel any api calls/setting of state when the component is unmounted? Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I found the basic answer here in this other question: Canceling an Axios REST call in React Hooks useEffects cleanup failing

Basically, I needed to have the useEffect function return something in order for it to be cleaned up. It is easier to explain in code, so I will put that below:

  useEffect(() => {
    let unMounted = false;
    const onLoad = async () => {
      const data= await axios.get();
      !unMounted &&
        setData(data);
    };

    onLoad();

    return () => {
      unMounted = true;
    };
  }, []);
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!