npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@pawells/react-graphql

v3.0.0

Published

React runtime companion providing Apollo Client setup, connection state management, and GraphQLProvider

Readme

React GraphQL Library

CI npm version Node License: MIT

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.0
    • graphql ^16.0.0
    • react >= 19.0.0
    • rxjs >= 7.0.0

Installation

npm install @pawells/react-graphql @apollo/client graphql react rxjs

Quick 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.ReactElement

React 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): IGraphQLClientResult

Creates a configured Apollo Client with HTTP and WebSocket transport. Configures:

  • Auth — bearer token injected into the HTTP Authorization header and WebSocket connectionParams. Accepts a static string or an async factory function.
  • RetryRetryLink with 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-ws with automatic reconnection on connection drop.
  • Error logging — optional console.error output 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(): GraphQLConnectionState

Returns the current WebSocket connection state. The component re-renders whenever the state changes.

useGraphQLReconnect

function useGraphQLReconnect(): () => void

Returns 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.