| 3 | |
| 4 | /** One tracker WS connection for the page lifetime + its live state. */ |
| 5 | export function useTracker(): { stream: TrackerStreamState; conn: TrackerConnection } { |
| 6 | const ref = useRef<TrackerConnection | null>(null); |
| 7 | if (!ref.current) ref.current = new TrackerConnection(); |
| 8 | const conn = ref.current; |
| 9 | |
| 10 | const [stream, setStream] = useState<TrackerStreamState>(conn.stream); |
| 11 | |
| 12 | useEffect(() => { |
| 13 | const unsub = conn.subscribe(setStream); |
| 14 | conn.connect(); |
| 15 | return () => { |
| 16 | unsub(); |
| 17 | conn.close(); |
| 18 | }; |
| 19 | }, [conn]); |
| 20 | |
| 21 | return { stream, conn }; |
| 22 | } |