Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 24.6 — Real-Time Updates
React · Example 2 of 3

A fake WebSocket: reconnect with backoff and merge without duplicates

FakeSocket behaves like a WebSocket (an EventTarget with open, message and close). The first connection drops; the hook waits 100ms and reconnects. The server resends message 2, and the merge skips it, so each message shows once, in order.

Live data reaches a React app in four ways: polling (ask on a timer), long polling (the server holds the request until something changes), Server-Sent Events (a one-way stream from the server) and WebSockets (a two-way connection); whichever you pick, the client must reconnect with backoff, merge updates into state without duplicates, and show presence and typing indicators that expire.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a usePolling(fn, ms) hook that calls fn immediately and then every ms, skips calls while the tab is hidden, and stops on unmount.

02

Write the backoff delay function with a 30-second cap and full jitter.

Explain it without notes

01

Compare polling, long polling, SSE and WebSockets.

02

How would you implement reliable reconnection for a WebSocket in React?

03

How do you merge live updates into existing state safely?

04

How would you implement a typing indicator?

A fake WebSocket: reconnect with backoff and merge without duplicates

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

connected (#1)
connection lost, retrying in 100ms
connected (#2)
Messages: Hi! | Anyone here? | Back online