Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Guard against opening duplicate stream connections
Before creating a new EventSource/WebSocket, return early if the ref already holds an open connection.
Bad example
| 1 | const connectStream = useCallback(() => { |
| 2 | const es = new EventSource(url); |
| 3 | streamRef.current = es; |
| 4 | es.onmessage = handleMessage; |
| 5 | }, []); |
Explanation (EN)
Calling connectStream again (retry, re-render, tab toggle) opens a second EventSource while the first is still live, doubling traffic and message handling.
Objašnjenje (HR)
Ponovni poziv connectStream (retry, re-render, prebacivanje taba) otvara drugi EventSource dok je prvi jos aktivan, sto udvostrucuje promet i obradu poruka.
Good example
| 1 | const connectStream = useCallback(() => { |
| 2 | if (streamRef.current) return; // already connected |
| 3 | const es = new EventSource(url); |
| 4 | streamRef.current = es; |
| 5 | es.onmessage = handleMessage; |
| 6 | }, []); |
Explanation (EN)
The early return makes connect idempotent: repeated calls are no-ops while a connection is alive.
Objašnjenje (HR)
Rani povratak cini connect idempotentnim: ponovljeni pozivi nemaju ucinak dok je veza aktivna.
Notes (EN)
Pair this with nulling the ref on close so the guard correctly allows reconnection.
Bilješke (HR)
Uparite ovo s postavljanjem ref-a na null pri zatvaranju kako bi guard ispravno dopustio ponovno povezivanje.