@pawells/react-graphql
v3.0.0
Published
React runtime companion providing Apollo Client setup, connection state management, and GraphQLProvider
Maintainers
Readme
React GraphQL Library
Description
@pawells/react-graphql is an Apollo Client (v4) setup library for React applications. It configures HTTP and WebSocket (graphql-ws) transports on a single client, tracks connection state across the Connecting → Connected → Reconnecting → Error lifecycle, and provides automatic reconnection with exponential backoff. A GraphQLProvider React component wraps ApolloProvider and makes connection state and manual reconnection available to the component tree via React context.
WebSocket security is enforced at client-creation time: wss:// is required in production. ws:// is only permitted when the hostname resolves to localhost (localhost, 127.0.0.1, or ::1). Passing any other ws:// URL causes CreateGraphQLClient to throw a BaseError with code GRAPHQL_INSECURE_WEBSOCKET.
Requirements
- Node >= 22.0.0
- Peer dependencies — install alongside this package:
@apollo/client>= 4.0.0graphql^16.0.0react>= 19.0.0rxjs>= 7.0.0
Installation
npm install @pawells/react-graphql @apollo/client graphql react rxjsQuick Start
Wrap your application root with GraphQLProvider, passing a TGraphQLClientOptions object.
import { GraphQLProvider } from '@pawells/react-graphql';
const graphqlOptions = {
name: 'my-app',
httpUri: 'https://api.example.com/graphql',
wsUri: 'wss://api.example.com/graphql/ws',
token: () => localStorage.getItem('auth-token') ?? '',
logGraphQLErrors: true,
logNetworkErrors: true,
};
export function Root() {
return (
<GraphQLProvider options={graphqlOptions} fallback={<p>Connecting...</p>}>
<App />
</GraphQLProvider>
);
}Use useConnectionState inside any descendant to read the live connection state:
import { useConnectionState, GraphQLConnectionState } from '@pawells/react-graphql';
export function ConnectionBanner() {
const state = useConnectionState();
if (state === GraphQLConnectionState.Reconnecting) {
return <p>Reconnecting to server...</p>;
}
if (state === GraphQLConnectionState.Error) {
return <p>Connection error.</p>;
}
return null;
}API Reference
Provider
GraphQLProvider
function GraphQLProvider(props: IGraphQLProviderProps): React.ReactElementReact component that creates an Apollo Client from options, mounts an ApolloProvider, and publishes connection state to GraphQLContext. Renders fallback (or nothing) until the client is ready. Disposes the client on unmount.
interface IGraphQLProviderProps {
options: TGraphQLClientOptions; // Client configuration
children: React.ReactNode; // Application subtree
fallback?: React.ReactNode; // Optional placeholder during initialization
}Pass a stable options reference (defined outside the render function or memoized) to prevent unnecessary client recreation.
Factory
CreateGraphQLClient
function CreateGraphQLClient(options: TGraphQLClientOptions): IGraphQLClientResultCreates a configured Apollo Client with HTTP and WebSocket transport. Configures:
- Auth — bearer token injected into the HTTP
Authorizationheader and WebSocketconnectionParams. Accepts a static string or an async factory function. - Retry —
RetryLinkwith exponential backoff: initial delay 1 s, max 10 s, jitter enabled, up to 10 attempts. - Fetch policy — all queries, watches, and mutations default to
no-cache. - WebSocket — managed by
graphql-wswith automatic reconnection on connection drop. - Error logging — optional
console.erroroutput for GraphQL and network errors (sanitized to omit sensitive fields).
Throws BaseError (code GRAPHQL_INSECURE_WEBSOCKET) when wsUri uses ws:// with a non-localhost hostname.
Hooks
Both hooks must be called inside GraphQLProvider.
useConnectionState
function useConnectionState(): GraphQLConnectionStateReturns the current WebSocket connection state. The component re-renders whenever the state changes.
useGraphQLReconnect
function useGraphQLReconnect(): () => voidReturns a callback that disposes the current client and creates a fresh one, triggering a new connection sequence. Useful for building manual reconnect controls.
Types
TGraphQLClientOptions
Configuration object passed to CreateGraphQLClient and GraphQLProvider.
| Property | Type | Required | Description |
|---|---|---|---|
| name | string | Yes | Client identifier, forwarded to Apollo DevTools via devtools.name. |
| httpUri | string | Yes | GraphQL HTTP endpoint URI. |
| wsUri | string | Yes | GraphQL WebSocket endpoint URI. wss:// required in production; ws:// permitted for localhost only. |
| token | string \| (() => string \| Promise<string>) | No | Static bearer token or async token provider. |
| logGraphQLErrors | boolean | No | Log GraphQL errors to the console. |
| logNetworkErrors | boolean | No | Log network errors to the console. |
| cache | ApolloCache \| undefined | No | Apollo cache instance (any ApolloCache subtype accepted). A new InMemoryCache is created if omitted. |
| persistCache | boolean | No | Reserved — has no effect in the current release. Intended for future cache-persistence support. |
IGraphQLClientResult
Return value of CreateGraphQLClient.
| Property | Type | Description |
|---|---|---|
| client | ApolloClient | Configured Apollo Client instance. |
| dispose | TDisposeFunction | Stops the WebSocket connection and Apollo Client. Call on teardown. |
| getConnectionState | () => GraphQLConnectionState | Returns the current connection state without subscribing. |
| onStateChange | (handler: (state: GraphQLConnectionState) => void) => () => void | Subscribes to connection state changes. Returns an unsubscribe function. |
IGraphQLContextValue
Context value provided by GraphQLProvider via React Context.
| Property | Type | Description |
|---|---|---|
| connectionState | GraphQLConnectionState | Current WebSocket connection state. |
| reconnect | () => void | Function to manually trigger a reconnection attempt. |
TDisposeFunction
type TDisposeFunction = () => void;Cleanup callback that terminates the WebSocket connection and stops the Apollo Client. Called automatically by GraphQLProvider on unmount.
TGraphQLConnectionEvent
interface TGraphQLConnectionEvent {
state: GraphQLConnectionState;
error?: unknown;
}Describes a connection state change. The error field is populated when state is GraphQLConnectionState.Error.
GraphQLConnectionState
Enum representing the WebSocket connection lifecycle.
| Value | String | Description |
|---|---|---|
| GraphQLConnectionState.Connecting | 'Connecting' | Client is establishing the initial connection. |
| GraphQLConnectionState.Connected | 'Connected' | Connection is open and healthy. |
| GraphQLConnectionState.Reconnecting | 'Reconnecting' | Connection dropped; automatic reconnection is in progress. |
| GraphQLConnectionState.Error | 'Error' | A connection error has occurred. |
License
MIT — See LICENSE for details.
