fetch sends one request and waits for one answer. For order updates, chat or anything else the server pushes, React Native supports WebSockets, which give you full-duplex communication over a single TCP connection. WebSocket is a global like fetch, and most of its API matches the browser's, but sending at the wrong moment throws, and a failed connection explains itself in a different event from the one you might check.
Key terms
readyState: the socket's current state, one ofCONNECTING(0),OPEN(1),CLOSING(2) orCLOSED(3).CloseEvent: the event passed toonclose, carrying a numericcodeand areasonstring.CLOSE_ABNORMAL: close code 1006, the RFC 6455 code for an abnormal closure where no code was provided in a control frame, which React Native reports when a connection fails.binaryType: the property that chooses whether binary messages arrive as anArrayBufferor aBlob.
Four handlers for one connection
A new WebSocket starts with readyState set to CONNECTING. When the native side reports the connection open, readyState becomes OPEN, protocol holds the negotiated subprotocol and an open event fires. Each message from the server then arrives as a message event with the payload in data. Binary payloads come as an ArrayBuffer unless you set binaryType to 'blob', and any value other than 'blob' or 'arraybuffer' throws.
onopen, onmessage, onerror and onclose are handler properties for the open, message, error and close events. React Native's WebSocket extends EventTarget, so addEventListener also works when more than one part of the app listens to the same socket. In the TypeScript types, onopen takes no argument and onmessage receives a WebSocketMessageEvent.
send waits for OPEN
Calling send() while readyState is CONNECTING throws an Error with the message INVALID_STATE_ERR, and so does ping(). Since every socket starts out connecting, a send() on the line after new WebSocket(...) always throws. Send the first message from onopen, as the useOrderFeed hook does with its subscribe message, and guard later sends with a state check:
tsxif (socket?.readyState === WebSocket.OPEN) { socket.send(JSON.stringify({type: 'note', orderId, note})); }
The constants exist as static properties on WebSocket and on each instance. Compare against OPEN rather than testing for CONNECTING: the JavaScript check in send() covers CONNECTING only, and nothing in it stops a send on a CLOSING or CLOSED socket.
send() accepts a string, an ArrayBuffer or a view on one, or a Blob. Anything else throws Unsupported data type, so objects go through JSON.stringify first.
Headers on the connection
The constructor takes up to three arguments: the URL, optional protocols (a string or an array of strings) and an options object whose headers field maps header names to string values. React Native hands those headers to the native connect call, so this is where an Authorization header for the connection goes.
headers is the only option React Native keeps. A top-level origin is deprecated: it logs a warning and gets moved into headers. Any other top-level key is warned about and discarded, with a hint asking whether you meant to put it under headers, so a token passed as {token: accessToken} never leaves the device.
Reading why a connection ended
close() with no arguments uses code 1000 (CLOSE_NORMAL) and an empty reason. On a socket that is already CLOSING or CLOSED it does nothing. Otherwise it sets readyState to CLOSING and asks the native side to close. When the connection closes, readyState becomes CLOSED and onclose receives the code and reason. React Native doesn't set wasClean on that event, so it reads false even after a normal close.
A connection that fails goes through a different sequence. readyState becomes CLOSED, a plain error event fires, and then a close event arrives with code 1006 and the native failure message as its reason. The networking guide's example logs e.message in onerror, and the TypeScript types declare a message field on that event, but the event React Native dispatches is a plain Event with no message. Read code and reason in onclose instead, as useOrderFeed does. Both fields are optional in the TypeScript types, so give them a fallback.
Code Examples
import {useEffect, useRef, useState} from 'react';
type OrderUpdate = {orderId: string; status: string};
export function useOrderFeed(accessToken: string) {
const socketRef = useRef<WebSocket | null>(null);
const [updates, setUpdates] = useState<OrderUpdate[]>([]);
const [closeInfo, setCloseInfo] = useState<string | null>(null);
useEffect(() => {
const socket = new WebSocket('wss://api.example.com/orders/live', null, {
headers: {Authorization: `Bearer ${accessToken}`},
});
socketRef.current = socket;
socket.onopen = () => {
// readyState is OPEN here, so send() no longer throws
socket.send(JSON.stringify({type: 'subscribe', channel: 'orders'}));
};
socket.onmessage = event => {
if (typeof event.data === 'string') {
const update = JSON.parse(event.data) as OrderUpdate;
setUpdates(previous => [update, ...previous]);
}
};
socket.onclose = event => {
// A failed connection ends here with code 1006 and the failure message as reason
setCloseInfo(`Closed with code ${event.code ?? 0}: ${event.reason ?? ''}`);
};
return () => socket.close();
}, [accessToken]);
const sendNote = (orderId: string, note: string) => {
const socket = socketRef.current;
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({type: 'note', orderId, note}));
}
};
return {updates, closeInfo, sendNote};
}