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
Param | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by gql . |
options
Name / Type | Description |
Operation options | |
| 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. |
| 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 |
Networking options | |
| If you're using Apollo Link, this object is the initial value of the |
| If The default value is |
| The instance of By default, the instance that's passed down via context is used, but you can provide a different instance here. |
Caching options | |
| 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 The default value is |
Result
Name / Type | Description |
Query reference | |
| In order to link a query initiated by a specific |
Helper functions | |
| A function that enables you to re-execute the query, optionally passing in new To guarantee that the refetch performs a network request, its Calling this function will cause the component to re-suspend, unless the call site is wrapped in |
| 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 |
useReadQuery
API
Function Signature
function useReadQuery<TData>(queryRef: QueryReference<TData>): {data: TData;networkStatus: NetworkStatus;error: ApolloError | undefined;} {}
Params
queryRef
Param | Type | Description |
---|---|---|
queryRef | QueryReference | The queryRef that was generated via useBackgroundQuery . |
Result
Name / Type | Description |
Operation result | |
| An object containing the result of your GraphQL query after it completes. This value might be |
| If the query produces one or more errors, this object contains either an array of This property can be ignored when using the default |
| 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 id
s.
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 | |
| Required. An object containing a |
| Required. A GraphQL fragment document parsed into an AST with the |
| The name of the fragment defined in the Required if the |
| If The default value is |
| 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. |
| If The default value is |
| If The default value is |
Result
Name / Type | Description |
---|---|
Operation result | |
| An object containing the data for a given GraphQL fragment. This value might be |
| A boolean indicating whether the data returned for the fragment is complete. When |
| A tree of all |
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
Param | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by gql . |
options
Name / Type | Description |
Operation options | |
| 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. |
| 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 |
Networking options | |
| If you're using Apollo Link, this object is the initial value of the |
| If The default value is |
| The instance of By default, the instance that's passed down via context is used, but you can provide a different instance here. |
Caching options | |
| 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 The default value is |
| If The default value is |
| Watched queries must opt into overwriting existing data on refetch, by passing The default value is |
Result
Name / Type | Description |
Operation result | |
| An object containing the result of your GraphQL query after it completes. This value might be |
| If the query produces one or more errors, this object contains either an array of This property can be ignored when using the default |
| A number indicating the current network state of the query's associated request. See possible values. |
Client | |
| 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 | |
| A function that enables you to re-execute the query, optionally passing in new To guarantee that the refetch performs a network request, its Calling this function will cause the component to re-suspend, , unless the call site is wrapped in |
| 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 |
| 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. |