Skip to main content
@archie/react-sdk provides React hooks, a provider, and components for your Archie backend. It builds on @archie/js-sdk and adds reactive auth state, declarative data fetching, real-time subscriptions, file uploads with progress tracking, and route guards. Use it when you build a React frontend that talks to an Archie project. The package is available on npm.

Installation

Install the React SDK together with the JavaScript SDK.
Peer dependencies: react >=18 and @archie/js-sdk.

Quick start

Create a client with createClient, wrap your app in ArchieProvider, and use the hooks in any child component.

ArchieProvider

ArchieProvider makes the Archie client and the auth session available to every hook through React context.
On mount, the provider calls client.auth.waitForInit() to restore a persisted session. It then subscribes to onAuthStateChange and keeps the session in context up to date. All child hooks read { client, session, isLoading } from this context.

Client options

The provider uses the options you pass to createClient(). Hooks inherit these options automatically. Retries cover transient errors (429, 500, 502, 503, 504, and network failures) with exponential backoff and jitter. You can also pass a logger, such as consoleLogger from @archie/js-sdk.

Hooks

useArchieClient

useArchieClient returns the raw ArchieClient instance. Use it for advanced cases outside the provided hooks.
useArchieClient throws if you call it outside <ArchieProvider>.

useAuth

useAuth exposes the full authentication state and operations. All async methods return { data/session, error } and never throw.
exchangeCode takes a single-use code from a trusted server. A session created this way cannot be refreshed. All methods are memoized with useCallback, so you can pass them as props without causing extra re-renders.
The session updates in context automatically, so you do not need to set state yourself.

useQuery

useQuery runs declarative GraphQL queries with caching, stale-while-revalidate, polling, and automatic deduplication.
Options Return values Behavior
  • Stale-while-revalidate: shows cached data immediately and refetches in the background.
  • Deduplication: components with the same query and variables share a single network request.
  • Auto-refetch on auth change: when the user’s token changes, all active queries refetch.
  • Auto-refetch on invalidation: a mounted query re-runs as soon as its key is invalidated, for example by a useMutation with invalidateQueries. Concurrent consumers of the same key still share one request.
  • Latest response wins: a response already in flight when its key is invalidated is discarded, so pre-mutation data never repaints the view.
  • Errors never blank the view: a failed revalidation sets error but keeps the data already on screen.
  • Variable tracking: variables are compared with JSON.stringify, and the query refetches when they change.

useMutation

useMutation runs imperative GraphQL mutations and can invalidate cached queries.
Options Return values
invalidateQueries matches by substring. A pattern like 'id' refetches every mounted query whose text contains id, and each one is a real network request. Use patterns distinctive enough to name the entity you changed. You can pass several patterns, because the whole array is applied as one batch and a query matched more than once still refetches only once.

useSubscription

useSubscription opens a real-time GraphQL subscription over WebSocket. It subscribes on mount and unsubscribes on unmount.
Options Return values
The underlying @archie/js-sdk realtime module reconnects automatically with exponential backoff.

useFileUpload

useFileUpload uploads files and tracks progress.
FileUploadOptions is { filename?, contentType?, providerType?, onProgress? }.

useRest

useRest returns the REST module for imperative calls to your REST API.

useRestQuery

useRestQuery is a declarative hook for GET requests to custom REST endpoints.
The options extend RestRequestOptions ({ headers?, params?, signal? }) with enabled?: boolean.

useRestMutation

useRestMutation is an imperative hook for POST, PUT, PATCH, and DELETE requests.
The optional overrideOptions argument of execute lets you pass custom headers, params, or signal for a single request.

useNotifications

useNotifications subscribes to live in-app notifications and manages read state. It opens a WebSocket channel on mount and closes it on unmount.
Options Return values
Always call the hook unconditionally, to follow the React rules of hooks. When there is no authenticated user, pass receiverId='' and enabled: false. The hook then does not load or subscribe.
useNotifications pages backward through history without dropping or duplicating live items.
  • fetchMore() loads the next older page and appends it (deduplicated, newest first). It does nothing when !hasMore, when a fetch is already in flight, when the hook is disabled, or when a previous fetchMore failed. Call refetch(), or change receiverId or unreadOnly, to retry.
  • hasMore is true when more older records exist for the active filter.
  • isFetchingMore is true while a fetchMore() call is in flight. Use it to drive a “loading older” indicator.
Changing receiverId or unreadOnly resets pagination and re-seeds from the first page.
Before you render n.actionUrl as a link, check that its scheme is http: or https:. Never allow javascript: or data: URLs. Treat n.metadata and n.params as untrusted server data.

Components

AuthGuard

AuthGuard renders content based on authentication state and, optionally, user roles.
AuthGuard evaluates these rules in order:
1

Session is loading

It renders loadingComponent.
2

User is not authenticated

It renders fallback.
3

Roles required and the user has none of them

It renders fallback.
4

Otherwise

It renders children.
You can nest guards, for example to protect an admin area inside an authenticated layout:

Error handling

All useAuth methods return { data/session, error } and never throw. For useQuery, useMutation, and the other data hooks, errors appear in the error field of the return object. These error classes come from @archie/js-sdk:

Server-side rendering

All hooks are safe to use with server-side rendering (SSR):
  • Hooks do not access window or document on the initial render.
  • refetchOnWindowFocus checks typeof window before it adds listeners.
  • ArchieProvider initializes the session asynchronously, so it does not block SSR.
  • AuthGuard renders loadingComponent during server render when the session is unknown.
In frameworks like Next.js, create the client outside the component tree.

TypeScript

All hooks are generic, so you can type each response.

Re-exported types

@archie/react-sdk re-exports the essential types from @archie/js-sdk, so you can import from one package.

Health check

The client exposes ping() to check that your project is reachable.

Resources

@archie/react-sdk on npm

Package page, versions, and install instructions.

@archie/js-sdk on npm

The underlying client with retry, timeout, and custom fetch details.