Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda