Reconnecting WebSocket hooks
You can reconnect a mobile WebSocket with backoff and clean up its handlers so the customer map keeps receiving updates after network interruptions.
Learning outcomes
- Explain why a mobile WebSocket needs automatic reconnection when network connectivity changes.
- Calculate capped exponential backoff delays with jitter and construct an authenticated WebSocket URL.
- Manage socket connections, reconnect timers and cleanup through React's
useEffect. - Keep the latest message callback in a ref without restarting an active connection.
- Recover the latest order state after reconnecting because missed WebSocket messages are not replayed.
The customer order screen needs live order updates even when a phone temporarily loses its network connection. The rider screen also needs a connection for assignment and order events. A WebSocket can close when a customer enters an elevator or switches from Wi-Fi to mobile data, so the application must reconnect without requiring a screen restart.
The problem is not opening a connection. It is managing that connection throughout the lifetime of a React component. You need to control retry timing, keep the latest message callback available and release network resources when the screen disappears.
Persistent connections
The order tab from Week 4 uses Polling. It requests updated order information every 10 seconds. This works when occasional delays are acceptable, but it cannot deliver an update immediately.
A WebSocket provides a different communication model. The client establishes a persistent connection, and the backend can send messages whenever an order changes.
For example, when an order moves from PREPARING to READY, the backend can send an event without waiting for the customer's next polling request.
A persistent connection is not a permanent connection. Mobile networks change frequently, and a connection can close without the customer leaving the order screen.
The application needs a Reconnecting WebSocket that attempts to establish a new connection after an unexpected disconnection.
A reconnecting hook should handle three responsibilities:
- Construct the connection URL using the API base and access token.
- Calculate the delay before another connection attempt.
- Manage the connection lifecycle and deliver incoming messages to the current callback.
Keep these responsibilities separate. The URL and delay functions are ordinary TypeScript functions. The hook manages React state and the WebSocket lifecycle.
Exponential backoff
Immediately reconnecting after every disconnection creates unnecessary network traffic.
Imagine that a customer's internet connection disappears for 30 seconds. If the application retries every few milliseconds, it repeatedly sends requests that cannot succeed.
When thousands of customers experience the same outage, these retries create additional pressure on the backend.
Exponential backoff increases the waiting time between consecutive attempts. Start with a one-second delay and double the base delay after each unsuccessful attempt.
The base delay follows this sequence:
| Attempt | Base delay |
|---|---|
| 0 | 1 second |
| 1 | 2 seconds |
| 2 | 4 seconds |
| 3 | 8 seconds |
| 4 | 16 seconds |
| 5 | 30 seconds |
| 6 | 30 seconds |
The base delay stops increasing after 30 seconds. This prevents the application from waiting indefinitely long between attempts.
However, there is another problem. Suppose 10,000 customers lose their connection at the same time. Without additional variation, they could all attempt to reconnect at approximately the same time.
Jitter
Jitter introduces a random variation into the calculated delay. Multiply the base delay by a random factor between 0.5 and 1.5.
The required formula is:
Math.min(30000, 1000 * 2 ** attempt) * (0.5 + random())The attempt value determines the exponential base. The random() function supplies the variation.
JavaScript's Math.random() returns a value greater than or equal to zero and strictly less than one. Adding 0.5 produces a multiplier between 0.5 and 1.5, with the upper endpoint approached but not reached.
For example, a base delay of 4000 milliseconds can produce a delay between 2000 and approximately 6000 milliseconds.
The 30-second cap applies before jitter. Therefore, the actual delay can approach 45 seconds.
Calculating the retry delay
Put the calculation in app/lib/useSocket.ts. Keep it independent of React so you can test it without mounting a component.
export function nextDelay(
attempt: number,
random: () => number = Math.random
): number {
const base = Math.min(30000, 1000 * 2 ** attempt);
return base * (0.5 + random());
}The optional random argument makes the calculation deterministic during tests. Production calls use Math.random by default.
Consider these examples:
nextDelay(0, () => 0.5); // 1000
nextDelay(1, () => 0.5); // 2000
nextDelay(2, () => 0); // 2000
nextDelay(2, () => 0.999); // 5996
nextDelay(10, () => 0.5); // 30000The results show two separate behaviours. The exponential base increases with each attempt, while the random multiplier changes the actual waiting time.
Notice that the calculation does not require rounding. The returned value is a JavaScript number, which can be passed directly to setTimeout().
A successful connection resets the attempt counter. Otherwise, one temporary outage could leave the customer waiting near the maximum delay even after the network has recovered.
Constructing the WebSocket URL
The mobile application already has an API base URL and an access token from the authentication flow established in Week 3.
An ordinary API base might look like this:
http://192.168.1.5:8080The WebSocket endpoint uses a different protocol:
| HTTP protocol | WebSocket protocol |
|---|---|
http | ws |
https | wss |
The backend expects the access token as a query parameter:
GET /v1/ws?token=<access token>The authentication middleware verifies this token before upgrading the request. A missing or invalid token receives HTTP 401.
Build the URL in the same socket utility module:
export function socketUrl(
apiBase: string,
token: string
): string {
const base = apiBase
.replace(/\/$/, "")
.replace(/^http:/, "ws:")
.replace(/^https:/, "wss:");
return `${base}/v1/ws?token=${encodeURIComponent(token)}`;
}The function removes one trailing slash before appending /v1/ws. This prevents an API base ending in / from producing a URL with a doubled slash.
For example:
socketUrl("https://api.example.com", "abc");
// wss://api.example.com/v1/ws?token=abcToken encoding matters because access tokens or other credentials can contain characters with special meanings in URLs.
Consider this input:
socketUrl("http://localhost:8080", "a b&c=d");The resulting URL is:
ws://localhost:8080/v1/ws?token=a%20b%26c%3DdWithout encodeURIComponent, characters such as spaces and ampersands can change how the query string is interpreted.
Also account for token expiration. The access token lasts 15 minutes in this project. Reconnecting with an expired token will continue to fail authentication. The application must use its existing authentication flow to obtain a valid token and construct the updated socket URL.
The React effect lifecycle
A WebSocket is an external resource. It should not open every time React renders a component.
React's useEffect lets you synchronize a component with an external system. You can create the connection inside the effect and return a cleanup function that releases it.
This is Effect cleanup. React executes the cleanup when the component unmounts and before the effect runs again with changed dependencies.
A basic connection looks like this:
useEffect(() => {
const socket = new WebSocket(url);
socket.onopen = () => {
setConnected(true);
};
return () => {
socket.close();
setConnected(false);
};
}, [url]);This example opens one connection and closes it when the effect is cleaned up. It does not reconnect after an unexpected disconnection.
A complete lifecycle also needs to track:
- Whether the effect is still active.
- The current WebSocket connection.
- The pending reconnect timer.
- The current attempt counter.
- Whether the connection is established.
The hook exposes the connection state through its return value:
export function useOrderSocket(
url: string | null,
onMessage: (raw: string) => void
): { connected: boolean }A null URL means there is no connection to establish. When a valid URL becomes available, the effect can open the WebSocket.
Keep the connection effect dependent on url. Changing the endpoint or token should clean up the previous connection and establish a new one.
Reconnection after closure
The close event is the central place for scheduling another connection attempt.
When the socket closes unexpectedly, mark the connection as disconnected and calculate the next delay.
current.onclose = () => {
if (!active || socket !== current) return;
socket = null;
setConnected(false);
const delay = nextDelay(attempt);
attempt += 1;
timer = setTimeout(connect, delay);
};The active flag prevents reconnection after cleanup. The socket identity check prevents an old connection from affecting a newer connection.
When the new socket opens successfully, reset the attempt counter:
current.onopen = () => {
if (!active || socket !== current) return;
attempt = 0;
setConnected(true);
};This reset matters. After a successful connection, a later disconnection should begin with the initial backoff delay rather than continuing from an earlier outage.
Handle socket errors by closing the affected connection. Let the close handler schedule the reconnect. Keeping reconnection in one place avoids scheduling duplicate retry timers from multiple event handlers.
The retry timer also needs a reference. Without its identifier, cleanup cannot reliably cancel a pending reconnect.
Keeping the latest message handler
There is another React problem to solve. A parent component can create a new callback on every render.
Consider a callback that updates the order:
const onMessage = (raw: string) => {
const message = JSON.parse(raw);
setOrder(message);
};If the WebSocket effect depends directly on onMessage, every render can cause React to clean up the existing connection and establish another one.
That interrupts a connection which could have remained active.
A Handler ref solves this problem. A React ref retains its identity between renders, while its current property can hold the latest callback.
const handlerRef = useRef(onMessage);
useEffect(() => {
handlerRef.current = onMessage;
}, [onMessage]);The WebSocket event listener reads the callback from the ref:
current.onmessage = (event: MessageEvent) => {
if (typeof event.data === "string") {
handlerRef.current(event.data);
}
};The socket can now use the latest message handler without restarting whenever the parent renders.
The distinction is important:
urldetermines which connection the effect owns.onMessagedetermines how the application processes received data.handlerRef.currentprovides the current callback without changing the connection effect's dependencies.
The hook should receive the raw message string. Parsing and handling specific message types belong in the application libraries that consume the hook.
Cleanup and resource ownership
The hook owns the WebSocket and its reconnect timer. When its effect ends, it must release both resources.
Cleanup needs to perform these operations:
- Mark the connection lifecycle as inactive.
- Clear any pending reconnect timer.
- Detach the active socket's handlers.
- Close the active socket.
- Reset the connection state.
A simplified cleanup looks like this:
return () => {
active = false;
if (timer !== null) {
clearTimeout(timer);
}
const current = socket;
socket = null;
if (current) {
current.onopen = null;
current.onmessage = null;
current.onclose = null;
current.onerror = null;
current.close();
}
setConnected(false);
};Setting active to false before closing the socket is important. Closing a connection can trigger its close event. The active check prevents that event from scheduling another reconnect.
Detaching the handlers also prevents callbacks from an old connection from changing the state after cleanup.
There are two separate cleanup situations:
Component unmounting: The hook clears its timer, closes its connection and prevents further attempts.
URL changes: React cleans up the previous effect before running the effect with the new URL. The new connection then uses the updated endpoint or token.
A correct hook must also ensure that a reconnect timer cannot open a socket after the component has unmounted.
Missed messages and order recovery
Reconnecting restores communication, but it does not recover messages sent while the phone was disconnected.
Consider this sequence:
- The customer's order is
PREPARING. - The phone loses network connectivity.
- The backend sends an update changing the order to
PICKED_UP. - The WebSocket connection is closed.
- The phone reconnects.
The customer may have missed the transition event. A basic WebSocket connection does not automatically store or replay missed messages.
The existing order API provides the recovery mechanism. After a successful reconnect, fetch the latest order state and reconcile the customer screen.
This separates two responsibilities:
| Mechanism | Responsibility |
|---|---|
| WebSocket | Low-latency order and location notifications |
| Order API | Authoritative current order state |
| Reconnect logic | Restores the connection after an interruption |
For example, a socket message can update the timeline immediately while the order API remains the source of truth for the complete current order.
A production system may introduce message sequence numbers, acknowledgements and replay support when reliable event delivery is required. Those mechanisms are separate from the basic reconnecting hook.
The same limitation applies to rider assignment events. Reconnecting does not guarantee that every notification sent during an outage will arrive.
Testing the socket utilities
The retry calculation and URL construction should be tested independently of a real backend.
The Jest tests in app-tests/lib/socket.test.ts verify the following behaviours:
- The initial retry delay is 1000 milliseconds with the midpoint random value.
- The base delay doubles across attempts.
- The base delay is capped at 30000 milliseconds.
- Jitter changes the final delay.
- HTTP URLs become WebSocket URLs.
- HTTPS URLs become secure WebSocket URLs.
- One trailing slash is removed.
- The access token is URL-encoded.
Run the focused tests:
cd app-tests && npx jest lib/socketThe socket lifecycle should also be checked with a mocked WebSocket implementation. Verify that the hook opens a connection when mounted, schedules reconnection after closure and uses the latest message handler.
Then unmount the component while a reconnect timer is pending. The timer must be cleared, the active socket must close and no subsequent connection may open.
Finally, run the application TypeScript check:
cd app && npx tsc --noEmitFor the full rider and customer workflow, stop the API for 20 seconds and restart it. The customer tracking screen must reconnect without restarting the application.
Rider and customer integration
The reconnecting hook belongs in app/lib/useSocket.ts. Keep URL construction and retry calculation as pure functions, while the hook manages the connection lifecycle.
The rider and customer screens can use the same hook. Their message callbacks determine how each screen processes incoming events.
The customer screen also needs to recover its order state after reconnecting. Use the existing order API instead of assuming that the WebSocket replays missed messages.
The Rider mode and customer tracking screens exercise connects these pieces. It uses the hook alongside the existing order types and application state. Keep connection management separate from message parsing and screen-specific behaviour so both sides can use the same lifecycle logic.
Check your understanding
A customer loses connectivity while the application is open. With nextDelay(2, () => 0.5), how long should the next reconnect wait?
References
Everything above is explained on this page; these are where it comes from.