Long Polling Pattern and Reconnection Logic
Implement long polling with exponential backoff and automatic reconnection using useEffect and AbortController.
Long Polling Pattern and Reconnection Logic is a free React Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Long Polling Flow
Long polling works in a cycle: the client sends an HTTP request, the server holds the connection open until new data is available (or a timeout occurs, typically 30-60 seconds), the server responds with the data, and the client immediately fires another request. This creates a near-continuous connection with server-push characteristics.
Implementing Long Polling in useEffect
Long polling in React uses an async recursive function inside useEffect. The function makes a fetch request, processes the response, and then calls itself again. An AbortController signal stops the recursion when the component unmounts. The function loops as long as the component is mounted and no abort has been signaled.
AbortController for Cleanup
Create an AbortController at the top of the useEffect: pass controller.signal to every fetch call. In the cleanup function, call controller.abort(). This cancels any in-flight request when the component unmounts, preventing state updates on unmounted components and network resource leaks.
Exponential Backoff on Error
When a long poll request fails, do not immediately retry — wait before the next attempt. Exponential backoff doubles the delay on each consecutive failure: 1s, 2s, 4s, 8s, 16s, capping at 30s. This prevents hammering a failing server and allows time for transient issues to resolve. Reset the delay to 1s on a successful response.
Adding Jitter to Backoff
With many clients polling the same server, exponential backoff without jitter causes "thundering herd": all clients back off the same amount and retry simultaneously, overwhelming the server again. Add jitter by randomizing the delay: delay + Math.random() * delay. This spreads retries across a time window, reducing server load spikes.
Connection Status State
Maintain connection status state to reflect the polling lifecycle: isConnecting (initial connection or reconnecting after error), isConnected (last poll succeeded), isError (consecutive failures, max retries reached). Display this status in the UI so users understand the real-time data reliability.
Showing Next Poll Timer
During the backoff delay before the next retry, you can show a countdown: "Reconnecting in 8s..." with a progress indicator. Compute the retry timestamp when setting the backoff timer and update the display each second. This transparency reassures users that the app is actively trying to recover.
Recursive setTimeout vs setInterval
Use recursive setTimeout (call the next poll inside the response handler) rather than setInterval for polling. setInterval fires at fixed intervals regardless of how long the previous request took — long-running requests can cause overlapping polls. Recursive setTimeout only starts the next poll after the previous one completes.
Polling Interval Configuration
Expose the polling interval as a configuration option in your hook: useLongPoll({ url, interval: 5000 }). Different data sources need different freshness: a "who's online" indicator might poll every 30s, while a task status might poll every 5s. Avoid hardcoding intervals in implementation code.
Transitioning from Polling to SSE
As your API matures, you might replace polling with SSE for better efficiency. The React component using a polling hook should be abstracted from the transport layer. If your hook exposes the same interface (onData, status, error), switching from polling to EventSource underneath requires no changes in the component that consumes the hook.
Server-Side Timeout Handling
When the server holds a long-poll connection and no data arrives, it must respond with a timeout (200 with empty body, or 204 No Content) to prevent the connection from hanging indefinitely. The client then immediately polls again. This server-side timeout (30-60s) is separate from the client-side fetch timeout (longer, e.g. 90s).
Exponential Backoff Purpose
Why does long polling use exponential backoff when retrying after connection errors?
Lesson Recap: Long Polling
Long polling: client requests, server holds until data available or timeout, client re-requests immediately after response. Implement with recursive async fetch in useEffect and AbortController for cleanup. On error: exponential backoff (1s, 2s, 4s... capped at 30s) plus jitter to prevent thundering herd. Use recursive setTimeout over setInterval to prevent overlapping polls. Track isConnecting/isConnected/isError state for UI feedback.
Frequently asked questions
Is the “Long Polling Pattern and Reconnection Logic” lesson free?
Yes — the full text of “Long Polling Pattern and Reconnection Logic” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Long Polling Pattern and Reconnection Logic”?
Implement long polling with exponential backoff and automatic reconnection using useEffect and AbortController. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Long Polling Pattern and Reconnection Logic” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SSE vs WebSockets vs Polling Comparison
- Consuming SSE Streams in React with EventSource
- Long Polling Pattern and Reconnection Logic
- Building a Real-Time Notification Feed