U
React Guide

Example 10 · 30 min

Server-Sent Events

EventSource · useRef · useEffect cleanup · named events

Senior Level

The Question

"Build a React component that subscribes to a Server-Sent Event stream, displays live log entries colour-coded by level, and cleanly closes the connection when the component unmounts. Explain why EventSource auto-reconnects and when you would close it explicitly."

EventSourceuseEffect cleanupuseRef (ES handle)named eventsconnection stateonerror / auto-reconnect
idle

Press Connect to open the SSE stream…

EventSource auto-reconnects on drop — always call .close() in the useEffect cleanup to prevent orphaned connections.

SSE vs WebSockets vs Polling

SSE (this example)

One-way server → client over plain HTTP. Built-in auto-reconnect. Simple — just EventSource. Perfect for live feeds, log tails, and progress streams.

WebSockets

Bidirectional full-duplex channel. Higher complexity: custom server, manual reconnect logic. Best for chat, collaborative editing, or games.

Polling (Example 6)

Client repeatedly fetches on a timer. Simple but wasteful — every tick is a full HTTP round-trip even when nothing has changed.