Docs
Launch GraphOS Studio

Hooks (experimental)

Apollo Client experimental react hooks API reference


useBackgroundQuery and useReadQuery

Installation

⚠️ The useBackgroundQuery and useReadQuery hooks are currently at the beta stage in Apollo Client. If you have feedback on them, please let us know via GitHub issues.

Apollo Client has beta support for the useBackgroundQuery and useReadQuery hooks, which work with React's Suspense feature. You can install it via npm install @apollo/client@beta.

Using useBackgroundQuery and useReadQuery

Create and provide a SuspenseCache instance to your ApolloProvider.

import { SuspenseCache } from '@apollo/client';
const suspenseCache = new SuspenseCache();
<ApolloProvider suspenseCache={suspenseCache} />;

useBackgroundQuery allows a user to initiate a query outside of the component that will read and render the data with useReadQuery, which triggers the nearest Suspense boundary while the query is pending. This means a query can be initiated higher up in the React render tree and your application can begin requesting data before the component that has a dependency on that data begins rendering.

Ensure the component tree that uses useReadQuery is wrapped with React's Suspense component. Note that the useReadQuery hook returns only data, error and networkStatus (though networkStatus should rarely be needed). Since Suspense provides the tools to manage our application's loading states, useReadQuery does not return a loading boolean.

See the API references for useBackgroundQuery and useReadQuery for supported options.

import { Suspense } from 'react';
import {
ApolloClient,
InMemoryCache,
SuspenseCache,
useBackgroundQuery,
useReadQuery,
} from '@apollo/client';
const query = gql`
foo {
bar
}
`;
const suspenseCache = new SuspenseCache();
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
cache: new InMemoryCache()
});
function SuspenseFallback() {
return <div>Loading...</div>;
}
function Child({ queryRef }) {
const { data } = useReadQuery(queryRef);
return <div>{data.foo.bar}</div>;
}
function Parent() {
const [queryRef] = useBackgroundQuery(query);
return (
<Suspense fallback={<SuspenseFallback />}>
<Child queryRef={queryRef} />
</Suspense>
);
}
function App() {
return (
<ApolloProvider client={client} suspenseCache={suspenseCache}>
<ErrorBoundary fallback={<div>Error</div>}>
<Parent />
</ErrorBoundary>
</ApolloProvider>
);
}

useBackgroundQuery API

Function Signature

function useBackgroundQuery<
TData = any,
TVariables extends OperationVariables = OperationVariables
>(
query: query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: Omit<
SuspenseQueryHookOptions<TData, TVariables>,
'returnPartialData' | 'refetchWritePolicy'
>,
): UseBackgroundQueryResult<TData> {}

Params

query
ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by gql.
options
Name /
Type
Description

Operation options

variables

{ [key: string]: any }

An object containing all of the GraphQL variables your query requires to execute.

Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.

errorPolicy

ErrorPolicy

Specifies how the query handles a response that returns both GraphQL errors and partial results.

For details, see GraphQL error policies.

The default value is none, which causes the useReadQuery hook to throw the error.

Networking options

context

Record<string, any>

If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.

canonizeResults

Boolean

If true, result objects read from the cache will be canonized, which means deeply-equal objects will also be === (literally the same object), allowing much more efficient comparison of past/present results.

The default value is false.

client

ApolloClient

The instance of ApolloClient to use to execute the query.

By default, the instance that's passed down via context is used, but you can provide a different instance here.

Caching options

fetchPolicy

SuspenseQueryHookFetchPolicy

Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy. This hook only supports the cache-first, network-only, no-cache, and cache-and-network fetch policies.

The default value is cache-first.

Result

Name /
Type
Description

Query reference

queryRef

QueryReference<TData>

In order to link a query initiated by a specific useBackgroundQuery call to the place its data is consumed—which can be uniquely identified not only by the query and variables passed, but also the optional queryKey supplied by the user—the hook returns a queryRef that can later be read by useReadQuery.

Helper functions

refetch

(variables?: Partial<TVariables>) => Promise<ApolloQueryResult>

A function that enables you to re-execute the query, optionally passing in new variables.

To guarantee that the refetch performs a network request, its fetchPolicy is set to network-only (unless the original query's fetchPolicy is no-cache or cache-and-network, which also guarantee a network request).

Calling this function will cause the component to re-suspend, unless the call site is wrapped in startTransition.

fetchMore

({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult>

A function that helps you fetch the next set of results for a paginated list field.

Calling this function will cause the component to re-suspend, unless the call site is wrapped in startTransition.

useReadQuery API

Function Signature

function useReadQuery<TData>(
queryRef: QueryReference<TData>
): {
data: TData;
networkStatus: NetworkStatus;
error: ApolloError | undefined;
} {}

Params

queryRef
ParamTypeDescription
queryRefQueryReferenceThe queryRef that was generated via useBackgroundQuery.

Result

Name /
Type
Description

Operation result

data

TData

An object containing the result of your GraphQL query after it completes.

This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).

error

ApolloError

If the query produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.

This property can be ignored when using the default errorPolicy or an errorPolicy of none. The hook will throw the error instead of setting this property.

networkStatus

NetworkStatus

A number indicating the current network state of the query's associated request. See possible values.

useFragment

Installation

⚠️ The useFragment hook is currently at the beta stage in Apollo Client. If you have feedback on it, please let us know via GitHub issues.

Beginning with version 3.7.0, Apollo Client has preview support for the useFragment hook, which represents a lightweight live binding into the Apollo Client Cache. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. useFragment never triggers network requests of its own.

Note: this hook is named useFragment_experimental in 3.7.x and 3.8.0-alpha.x releases. In 3.8.0-beta.0 and greater it no longer has an _experimental suffix.

useFragment enables Apollo Client to broadcast very specific fragment results to individual components. Note that the useQuery hook remains the primary hook responsible for querying and populating data in the cache (see the API reference). As a result, the component reading the fragment data via useFragment is still subscribed to all changes in the query data, but receives updates only when that fragment's specific data change.

Using useFragment

A GraphQL fragment defines a subset of fields on a GraphQL type that can be used to specify component-level data dependencies or allow re-use between multiple queries and mutations. See the API reference.

Given the following fragment definition:

const ItemFragment = gql`
fragment ItemFragment on Item {
text
}
`;

We can first use the useQuery hook to retrieve a list of items with ids.

const listQuery = gql`
query {
list {
id
}
}
`;
function List() {
const { loading, data } = useQuery(listQuery);
return (
<ol>
{data?.list.map(item => (
<Item key={item.id} id={item.id}/>
))}
</ol>
);
}

We can then use useFragment from within the <Item> component to create a live binding for each item by providing the fragment document, fragmentName and object reference via from.

function Item(props: { id: number }) {
const { complete, data } = useFragment({
fragment: ItemFragment,
fragmentName: "ItemFragment",
from: {
__typename: "Item",
id: props.id,
},
});
return <li>{complete ? data!.text : "incomplete"}</li>;
}

useFragment can be used in combination with the @nonreactive directive in cases where list items should react to individual cache updates without rerendering the entire list. For more information, see the @nonreactive docs.

useFragment API

Supported options and result fields for the useFragment hook are listed below.

Most calls to useFragment can omit the majority of these options, but it's useful to know they exist.

Options

The useFragment hook accepts the following options:

Name /
Type
Description

Operation options

from

string | StoreObject | Reference

Required. An object containing a __typename and primary key fields (such as id) identifying the entity object from which the fragment will be retrieved, or a { __ref: "..." } reference, or a string ID (uncommon).

fragment

DocumentNode

Required. A GraphQL fragment document parsed into an AST with the gql template literal.

fragmentName

string

The name of the fragment defined in the fragment document to use in the call.

Required if the fragment document includes more than one fragment, optional otherwise.

optimistic

boolean

If true, readFragment returns optimistic results.

The default value is true.

variables

{ [key: string]: any }

An object containing all of the GraphQL variables your fragment requires.

Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.

returnPartialData

boolean

If true, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.

The default value is true.

canonizeResults

boolean

If true, result objects read from the cache will be canonized, which means deeply-equal objects will also be === (literally the same object), allowing much more efficient comparison of past/present results.

The default value is false.

Result

Name /
Type
Description

Operation result

data

TData

An object containing the data for a given GraphQL fragment.

This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).

complete

boolean

A boolean indicating whether the data returned for the fragment is complete. When false, the missing field should explain which fields were responsible for the incompleteness.

missing

MissingTree

A tree of all MissingFieldError messages reported during fragment reading, where the branches of the tree indicate the paths of the errors within the query result.

useSuspenseQuery

Installation

⚠️ The useSuspenseQuery hook is currently at the beta stage in Apollo Client. If you have feedback on it, please let us know via GitHub issues.

Apollo Client has beta support for the useSuspenseQuery hook, which works with React's Suspense feature. You can install it via npm install @apollo/client@beta.

Using useSuspenseQuery

Create and provide a SuspenseCache instance to your ApolloProvider.

import { SuspenseCache } from '@apollo/client';
const suspenseCache = new SuspenseCache();
<ApolloProvider suspenseCache={suspenseCache} />;

Write queries using useSuspenseQuery. Ensure the component is wrapped with React's Suspense component. Note that the hook returns only data and error: since Suspense provides the tools to manage our application's loading states, useSuspenseQuery does not return a loading boolean.

See the API reference for supported options.

import { Suspense } from 'react';
import { useSuspenseQuery } from '@apollo/client';
const listQuery = gql`
query {
list {
id
}
}
`;
function App() {
return (
<Suspense fallback={<Spinner />}>
<List />
</Suspense>
);
}
function List() {
const { data } = useSuspenseQuery(listQuery);
return (
<ol>
{data.list.map(item => <Item key={item.id} id={item.id}/>)}
</ol>
);
}

useSuspenseQuery API

Function Signature

function useSuspenseQuery<
TData = any,
TVariables extends OperationVariables = OperationVariables
>(
query: DocumentNode,
options?: SuspenseQueryHookOptions<TData, TVariables>,
): UseSuspenseQueryResult<TData, TVariables> {}

Params

query
ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by gql.
options
Name /
Type
Description

Operation options

variables

{ [key: string]: any }

An object containing all of the GraphQL variables your query requires to execute.

Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.

errorPolicy

ErrorPolicy

Specifies how the query handles a response that returns both GraphQL errors and partial results.

For details, see GraphQL error policies.

The default value is none, which causes the hook to throw the error.

Networking options

context

Record<string, any>

If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.

canonizeResults

Boolean

If true, result objects read from the cache will be canonized, which means deeply-equal objects will also be === (literally the same object), allowing much more efficient comparison of past/present results.

The default value is false.

client

ApolloClient

The instance of ApolloClient to use to execute the query.

By default, the instance that's passed down via context is used, but you can provide a different instance here.

Caching options

fetchPolicy

SuspenseQueryHookFetchPolicy

Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy. This hook only supports the cache-first, network-only, no-cache, and cache-and-network fetch policies.

The default value is cache-first.

returnPartialData

boolean

If true, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.

The default value is false.

refetchWritePolicy

"merge" | "overwrite"

Watched queries must opt into overwriting existing data on refetch, by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.

The default value is "overwrite".

Result

Name /
Type
Description

Operation result

data

TData

An object containing the result of your GraphQL query after it completes.

This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).

error

ApolloError

If the query produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.

This property can be ignored when using the default errorPolicy or an errorPolicy of none. The hook will throw the error instead of setting this property.

networkStatus

NetworkStatus

A number indicating the current network state of the query's associated request. See possible values.

Client

client

ApolloClient

The instance of Apollo Client that executed the query.

Can be useful for manually executing followup queries or writing data to the cache.

Helper functions

refetch

(variables?: Partial<TVariables>) => Promise<ApolloQueryResult>

A function that enables you to re-execute the query, optionally passing in new variables.

To guarantee that the refetch performs a network request, its fetchPolicy is set to network-only (unless the original query's fetchPolicy is no-cache or cache-and-network, which also guarantee a network request).

Calling this function will cause the component to re-suspend, , unless the call site is wrapped in startTransition.

fetchMore

({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult>

A function that helps you fetch the next set of results for a paginated list field.

Calling this function will cause the component to re-suspend, unless the call site is wrapped in startTransition.

subscribeToMore

(options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => void

A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.

This function returns another function that you can call to terminate the subscription.

Previous
Hooks
Next
Testing
Edit on GitHubEditForumsDiscord