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

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