I have a component that
endpoint prop doesn't change)subscribe on wsRefunsubscribe on wsRefThe 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.