ClientProvider, useClient with an optional client override, and provider props.
React
Provide an existing @defjs/core client to a React tree. This package does not create, cache, or dispose the client. Its entry is marked 'use client', so import it from client components. React 18 or later is required.
See the React guide.
ClientProvider
function ClientProvider(props: ClientProviderProps): React.FunctionComponentElement<React.ProviderProps<DerivableClient | null>>;Context provider. Pass the DerivableClient returned by createClient. A nested ClientProvider overrides the client for its subtree; useClient() reads the nearest one. Passing a different client changes the context value for descendants.
import { createClient, withEndpoint } from "@defjs/core";
import { ClientProvider } from "@defjs/react";
import type { ReactNode } from "react";
const client = createClient(withEndpoint("https://api.example.com"));
export function ApiProvider({ children }: { children: ReactNode }) {
return <ClientProvider client={client}>{children}</ClientProvider>;
}useClient()
function useClient(overrideClient?: DerivableClient): DerivableClient;useClient(overrideClient) prefers the explicit client; omitted or undefined reads the nearest ClientProvider. An Error is thrown only when neither source supplies a client. Zero-argument useClient() calls remain valid. Pass that client into an operation. The hook returns the DerivableClient that was supplied; call it with request options where the operation runs to derive a Client value. Do not pass it to a state setter, because setState(client) would call it as an updater. A derived Client value is not accepted by ClientProvider or useClient.
Always call useClient(explicitClient) at the top level of a component or custom Hook, even with an explicit client; not in an ordinary function or event callback. Do not write explicitClient ?? useClient(), which conditionally calls a Hook. The override does not write Context or create a provider, and the Hook still subscribes to Context.
- Returns the exact explicit client or nearest provided client.
- Throws an
Errorwhen neither an explicit client nor Context supplies a client.
ClientProviderProps
interface ClientProviderProps {
client: DerivableClient;
children?: ReactNode;
}client is required and owned by the application. children is optional: the tree that can call useClient.