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

139
Views
React - Race Condition in multiple useEffect's cleanup function

I have a component that

  1. Initiate a websocket ref on mount (endpoint prop doesn't change)
  2. When component comes into screen view, it calls the subscribe on wsRef
  3. When component goes out of screen view, it calls the unsubscribe on wsRef

The problem is on unmount the 2nd cleanup function fails because we already have closed the websocket by the 1st cleanup function.

So we are unable to unsubscribe as the websocket is not in OPEN state.

How to control the order of cleanup effects here?

function Comp({endpoint, isVisible, id}) {
  const wsRef = useRef(null);
  useEffect(() => {
    wsRef.current = new WebsocketClass(endpoint);
    return () => {              // [1] cleanup no 1
      wsRef.current.close();
      wsRef.current = null;
    }
  }, [endpoint]);


  useEffect(() => {
    if (isVisible) {
      wsRef.current.subscribe(id);
    }
    return () => {
      if (isVisible) {
        wsRef.current.unsubscribe(id); // [2] fails, this cleanup runs after [1]
      } 
    }
  }, [isVisible, id]);

}

If I re-order the two useEffect in my function, the problem seem to go away, but is it really a permanent solution here?

Also, I can't close the websocket in the unsubscribe cleanup because the component can stay mounted while it goes out of screen and comes back again as user scrolls back and forth.

about 4 years ago · Juan Pablo Isaza
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!