Hooks
Apollo Client react hooks API reference
The ApolloProvider component
The ApolloProvider component leverages React's Context API to make a configured Apollo Client instance available throughout a React component tree. This component can be imported directly from the @apollo/client package.
1import { ApolloProvider } from '@apollo/client';Props
| Option | Type | Description |
|---|---|---|
client | ApolloClient<TCache> | An ApolloClient instance. |
Example
1const client = new ApolloClient({
2 cache: new InMemoryCache(),
3 uri: "http://localhost:4000/graphql"
4});
5
6ReactDOM.render(
7 <ApolloProvider client={client}>
8 <MyRootComponent />
9 </ApolloProvider>,
10 document.getElementById('root'),
11);The ApolloConsumer component
One way to access the configured Apollo Client instance directly is to create an ApolloConsumer component and provide a render prop function as its child. The render prop function will be called with your ApolloClient instance as its only argument. You can think of the ApolloConsumer component as similar to the Consumer component from the React Context API.
Example
1import { ApolloConsumer } from '@apollo/client';
2
3function WithApolloClient() {
4 return (
5 <ApolloConsumer>
6 {client => 'We have access to the client!' /* do stuff here */}
7 </ApolloConsumer>
8 );
9}useQueryRequires ≥ 3.0.0
A hook for executing queries in an Apollo application.
To run a query within a React component, call useQuery and pass it a GraphQL query document.
When your component renders, useQuery returns an object from Apollo Client that contains loading, error, and data properties you can use to render your UI.
Refer to the Queries section for a more in-depth overview of
useQuery.
Example
1 import { gql, useQuery } from '@apollo/client';
2
3 const GET_GREETING = gql`
4 query GetGreeting($language: String!) {
5 greeting(language: $language) {
6 message
7 }
8 }
9 `;
10
11 function Hello() {
12 const { loading, error, data } = useQuery(GET_GREETING, {
13 variables: { language: 'english' },
14 });
15 if (loading) return <p>Loading ...</p>;
16 return <h1>Hello {data.greeting.message}!</h1>;
17 }Signature
1useQuery<TData, TVariables>(
2 query: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
4): InteropQueryResult<TData, TVariables>Parameters
A GraphQL query document parsed into an AST by gql.
Options to control how the query is executed.
Show/hide child attributes
ApolloClient<any>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.
ErrorPolicySpecifies 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, meaning that the query result includes error details but not partial results.
booleanIf true, the query is not executed.
The default value is false.
TVariablesAn 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.
(data: MaybeMasked<TData>) => void⚠️ Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the related issue on GitHub.
A callback function that's called when your query successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).
This function is passed the query's result data.
(error: ApolloError) => void⚠️ Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the related issue on GitHub.
A callback function that's called when the query encounters one or more errors (unless errorPolicy is ignore).
This function is passed an ApolloError object that contains either a networkError object or a graphQLErrors array, depending on the error(s) that occurred.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
If true, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.
The default value is false.
numberSpecifies the interval (in milliseconds) at which the query polls for updated results.
The default value is 0 (no polling).
() => booleanA callback function that's called whenever a refetch attempt occurs while polling. If the function returns true, the refetch is skipped and not reattempted until the next poll interval.
booleanPass false to skip executing the query during server-side rendering.
WatchQueryFetchPolicySpecifies 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.
The default value is cache-first.
WatchQueryFetchPolicyDefaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchQueryFetchPolicy to revert back to whenever variables change (unless nextFetchPolicy intervenes).
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy)Specifies the FetchPolicy to be used after this query has completed.
RefetchWritePolicySpecifies whether a NetworkStatus.refetch operation should merge incoming field data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with Apollo Client 3.x.
booleanIf 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.
boolean⚠️ Deprecated
Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option.canonizeResultswill be removed in Apollo Client 4.0.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
boolean⚠️ Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It will be removed in Apollo Client 4.0.
If true, causes a query refetch if the query result is detected as partial.
The default value is false.
Result
Query result objectInteropQueryResult<TData, TVariables>Show/hide child attributes
MaybeMasked<TData> | undefinedAn 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).
ApolloErrorIf the query produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.
For more information, see Handling operation errors.
MaybeMasked<TData>An object containing the result from the most recent previous execution of this query.
This value is undefined if this is the query's first execution.
TVariables | undefinedAn object containing the variables that were provided for the query.
ApolloClient<any>The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.
booleanIf true, the query is still in flight and results have not yet been returned.
NetworkStatusA number indicating the current network state of the query's associated request. See possible values.
Used in conjunction with the notifyOnNetworkStatusChange option.
boolean⚠️ Deprecated
calledwill be removed from theuseQueryresult in Apollo Client 4.0.Recommended now
Please remove the use of the
calledproperty.
If true, the associated lazy query has been executed.
This field is only present on the result object returned by useLazyQuery.
<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & {
updateQuery?: (previousQueryResult: Unmasked<TData>, options: {
fetchMoreResult: Unmasked<TFetchData>;
variables: TFetchVars;
}) => Unmasked<TData>;
}) => Promise<ApolloQueryResult<MaybeMasked<TFetchData>>>A function that helps you fetch the next set of results for a paginated list field.
(variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>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).
See also Refetching.
(pollInterval: number) => voidA function that instructs the query to begin re-executing at a specified interval (in milliseconds).
() => voidA function that instructs the query to stop polling after a previous call to startPolling.
SubscribeToMoreFunction<TData, TVariables>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.
(mapFn: UpdateQueryMapFn<TData, TVariables>) => voidA function that enables you to update the query's cached result without executing a followup GraphQL operation.
See using updateQuery and updateFragment for additional information.
ObservableQuery<TData, TVariables>A reference to the internal ObservableQuery used by the hook.
ReadonlyArray<GraphQLFormattedError>⚠️ Deprecated
This property will be removed in a future version of Apollo Client. Please use
error.graphQLErrorsinstead.
useLazyQueryRequires ≥ 3.0.0
A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.
Refer to the Queries - Manual execution with useLazyQuery section for a more in-depth overview of
useLazyQuery.
Example
1 import { gql, useLazyQuery } from "@apollo/client";
2
3 const GET_GREETING = gql`
4 query GetGreeting($language: String!) {
5 greeting(language: $language) {
6 message
7 }
8 }
9 `;
10
11 function Hello() {
12 const [loadGreeting, { called, loading, data }] = useLazyQuery(
13 GET_GREETING,
14 { variables: { language: "english" } }
15 );
16 if (called && loading) return <p>Loading ...</p>
17 if (!called) {
18 return <button onClick={() => loadGreeting()}>Load greeting</button>
19 }
20 return <h1>Hello {data.greeting.message}!</h1>;
21 }Signature
1useLazyQuery<TData, TVariables>(
2 query: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: LazyQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
4): LazyQueryResultTuple<TData, TVariables>Parameters
A GraphQL query document parsed into an AST by gql.
Default options to control how the query is executed.
Show/hide child attributes
ApolloClient<any>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.
ErrorPolicySpecifies 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, meaning that the query result includes error details but not partial results.
TVariablesAn 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.
(data: MaybeMasked<TData>) => void⚠️ Deprecated
This option will be removed in Apollo Client 4.0. For more context, please see the related issue on GitHub.
A callback function that's called when your query successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).
This function is passed the query's result data.
(error: ApolloError) => void⚠️ Deprecated
This option will be removed in Apollo Client 4.0. For more context, please see the related issue on GitHub.
A callback function that's called when the query encounters one or more errors (unless errorPolicy is ignore).
This function is passed an ApolloError object that contains either a networkError object or a graphQLErrors array, depending on the error(s) that occurred.
If true, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.
The default value is false.
numberSpecifies the interval (in milliseconds) at which the query polls for updated results.
The default value is 0 (no polling).
() => booleanA callback function that's called whenever a refetch attempt occurs while polling. If the function returns true, the refetch is skipped and not reattempted until the next poll interval.
booleanPass false to skip executing the query during server-side rendering.
DefaultContext⚠️ Deprecated
contextwill be removed in Apollo Client 4.0.Recommended now
Please pass
contextto the returnedexecutefunction instead.
If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
WatchQueryFetchPolicySpecifies 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.
The default value is cache-first.
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy)Specifies the FetchPolicy to be used after this query has completed.
RefetchWritePolicySpecifies whether a NetworkStatus.refetch operation should merge incoming field data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with Apollo Client 3.x.
booleanIf 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.
WatchQueryFetchPolicy⚠️ Deprecated
initialFetchPolicywill be removed in Apollo Client 4.0.Recommended now
Please use
fetchPolicyinstead.
Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchQueryFetchPolicy to revert back to whenever variables change (unless nextFetchPolicy intervenes).
boolean⚠️ Deprecated
Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option.canonizeResultswill be removed in Apollo Client 4.0.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
boolean⚠️ Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It will be removed in Apollo Client 4.0.
If true, causes a query refetch if the query result is detected as partial.
The default value is false.
Result
1[execute: LazyQueryExecFunction<TData, TVariables>, result: QueryResult<TData, TVariables>]execute(options?: LazyQueryHookOptions<TVariables>) => Promise<LazyQueryResult<TData, TVariables>>useLazyQuery behaves just like useQuery. The useLazyQuery function returns a promise that fulfills with a query result when the query succeeds or fails.resultQueryResult<TData, TVariables>useQuery hook for more details.Show/hide child attributes
MaybeMasked<TData> | undefinedAn 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).
ApolloErrorIf the query produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.
For more information, see Handling operation errors.
MaybeMasked<TData>An object containing the result from the most recent previous execution of this query.
This value is undefined if this is the query's first execution.
TVariables | undefinedAn object containing the variables that were provided for the query.
booleanIf true, the associated lazy query has been executed.
This field is only present on the result object returned by useLazyQuery.
ApolloClient<any>The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.
booleanIf true, the query is still in flight and results have not yet been returned.
NetworkStatusA number indicating the current network state of the query's associated request. See possible values.
Used in conjunction with the notifyOnNetworkStatusChange option.
<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & {
updateQuery?: (previousQueryResult: Unmasked<TData>, options: {
fetchMoreResult: Unmasked<TFetchData>;
variables: TFetchVars;
}) => Unmasked<TData>;
}) => Promise<ApolloQueryResult<MaybeMasked<TFetchData>>>A function that helps you fetch the next set of results for a paginated list field.
(variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>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).
See also Refetching.
(pollInterval: number) => voidA function that instructs the query to begin re-executing at a specified interval (in milliseconds).
() => voidA function that instructs the query to stop polling after a previous call to startPolling.
SubscribeToMoreFunction<TData, TVariables>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.
(mapFn: UpdateQueryMapFn<TData, TVariables>) => voidA function that enables you to update the query's cached result without executing a followup GraphQL operation.
See using updateQuery and updateFragment for additional information.
ObservableQuery<TData, TVariables>A reference to the internal ObservableQuery used by the hook.
ReadonlyArray<GraphQLFormattedError>⚠️ Deprecated
This property will be removed in a future version of Apollo Client. Please use
error.graphQLErrorsinstead.
useMutationRequires ≥ 3.0.0
Refer to the Mutations section for a more in-depth overview of
useMutation.
Example
1 import { gql, useMutation } from '@apollo/client';
2
3 const ADD_TODO = gql`
4 mutation AddTodo($type: String!) {
5 addTodo(type: $type) {
6 id
7 type
8 }
9 }
10 `;
11
12 function AddTodo() {
13 let input;
14 const [addTodo, { data }] = useMutation(ADD_TODO);
15
16 return (
17 <div>
18 <form
19 onSubmit={e => {
20 e.preventDefault();
21 addTodo({ variables: { type: input.value } });
22 input.value = '';
23 }}
24 >
25 <input
26 ref={node => {
27 input = node;
28 }}
29 />
30 <button type="submit">Add Todo</button>
31 </form>
32 </div>
33 );
34 }Signature
1useMutation<TData, TVariables, TContext, TCache>(
2 mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: MutationHookOptions<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>
4): MutationTuple<TData, TVariables, TContext, TCache>Parameters
A GraphQL mutation document parsed into an AST by gql.
Options to control how the mutation is executed.
Show/hide child attributes
If true, makes sure all queries included in refetchQueries are completed before the mutation is considered complete.
The default value is false (queries are refetched asynchronously).
ErrorPolicySpecifies how the mutation handles a response that returns both GraphQL errors and partial results.
For details, see GraphQL error policies.
The default value is none, meaning that the mutation result includes error details but not partial results.
(data: MaybeMasked<TData>, clientOptions?: BaseMutationOptions) => voidA callback function that's called when your mutation successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).
This function is passed the mutation's result data and any options passed to the mutation.
(error: ApolloError, clientOptions?: BaseMutationOptions) => voidA callback function that's called when the mutation encounters one or more errors (unless errorPolicy is ignore).
This function is passed an ApolloError object that contains either a networkError object or a graphQLErrors array, depending on the error(s) that occurred, as well as any options passed the mutation.
OnQueryUpdated<any>Optional callback for intercepting queries whose cache data has been updated by the mutation, as well as any queries specified in the refetchQueries: [...] list passed to client.mutate.
Returning a Promise from onQueryUpdated will cause the final mutation Promise to await the returned Promise. Returning false causes the query to be ignored.
((result: FetchResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesIncludeAn array (or a function that returns an array) that specifies which queries you want to refetch after the mutation occurs.
Each array value can be either:
An object containing the
queryto execute, along with anyvariablesA string indicating the operation name of the query to refetch
TVariablesAn object containing all of the GraphQL variables your mutation requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
boolean⚠️ Deprecated
This option will be removed in Apollo Client 4.0. If you don't want to synchronize your component state with the mutation, please use
useApolloClientto get your ApolloClient instance and callclient.mutatedirectly.
If true:
The initial state update (setting loading to true) is skipped - The success state update (setting data and setting loading to false) is skipped - Error updates will still occur
The default value is false.
This option is useful when you want to execute a mutation but don't need to track its progress or result in the UI, potentially improving performance by reducing re-renders.
ApolloClient<object>The instance of ApolloClient to use to execute the mutation.
By default, the instance that's passed down via context is used, but you can provide a different instance here.
TContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
If true, the in-progress mutation's associated component re-renders whenever the network status changes or a network error occurs.
The default value is false.
MutationFetchPolicyProvide no-cache if the mutation's result should not be written to the Apollo Client cache.
The default value is network-only (which means the result is written to the cache).
Unlike queries, mutations do not support fetch policies besides network-only and no-cache.
Unmasked<NoInfer<TData>> | ((vars: TVariables, { IGNORE }: {
IGNORE: IgnoreModifier;
}) => Unmasked<NoInfer<TData>> | IgnoreModifier)By providing either an object or a callback function that, when invoked after a mutation, allows you to return optimistic data and optionally skip updates via the IGNORE sentinel object, Apollo Client caches this temporary (and potentially incorrect) response until the mutation completes, enabling more responsive UI updates.
For more information, see Optimistic mutation results.
MutationUpdaterFunction<TData, TVariables, TContext, TCache>A function used to update the Apollo Client cache after the mutation completes.
For more information, see Updating the cache after a mutation.
booleanTo avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4+ automatically clears any ROOT_MUTATION fields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing keepRootFields: true to the mutation. ROOT_MUTATION result data are also passed to the mutation update function, so we recommend obtaining the results that way, rather than using this option, if possible.
MutationQueryReducersMap<TData>A MutationQueryReducersMap, which is map from query names to mutation query reducers. Briefly, this map defines how to incorporate the results of the mutation into the results of queries that are currently being watched by your application.
Result
1[
2 mutate: (options?: MutationFunctionOptions<TData, TVariables>) => Promise<FetchResult<TData>>,
3 result: MutationResult<TData>
4]mutate(
options?: MutationFunctionOptions<TData, TVariables>
) => Promise<FetchResult<TData>>awaitRefetchQueriescontextfetchPolicyonCompletedonErroroptimisticResponserefetchQueriesonQueryUpdatedupdatevariablesclient
useMutation.The mutate function returns a promise that fulfills with your mutation result.resultMutationResult<TData>Show/hide child attributes
booleanIf true, the mutation's mutate function has been called.
ApolloClient<object>The instance of Apollo Client that executed the mutation.
Can be useful for manually executing followup operations or writing data to the cache.
MaybeMasked<TData> | nullThe data returned from your mutation. Can be undefined if ignoreResults is true.
ApolloErrorIf the mutation produces one or more errors, this object contains either an array of graphQLErrors or a single networkError. Otherwise, this value is undefined.
For more information, see Handling operation errors.
booleanIf true, the mutation is currently in flight.
() => voidA function that you can call to reset the mutation's result to its initial, uncalled state.
useSubscriptionRequires ≥ 3.0.0
Refer to the Subscriptions section for a more in-depth overview of
useSubscription.
Consider using onData instead of useEffect
If you want to react to incoming data, please use the onData option instead of useEffect. State updates you make inside a useEffect hook might cause additional rerenders, and useEffect is mostly meant for side effects of rendering, not as an event handler. State updates made in an event handler like onData might - depending on the React version - be batched and cause only a single rerender.
Consider the following component:
1export function Subscriptions() {
2 const { data, error, loading } = useSubscription(query);
3 const [accumulatedData, setAccumulatedData] = useState([]);
4
5 useEffect(() => {
6 setAccumulatedData((prev) => [...prev, data]);
7 }, [data]);
8
9 return (
10 <>
11 {loading && <p>Loading...</p>}
12 {JSON.stringify(accumulatedData, undefined, 2)}
13 </>
14 );
15}Instead of using useEffect here, we can re-write this component to use the onData callback function accepted in useSubscription's options object:
1export function Subscriptions() {
2 const [accumulatedData, setAccumulatedData] = useState([]);
3 const { data, error, loading } = useSubscription(
4 query,
5 {
6 onData({ data }) {
7 setAccumulatedData((prev) => [...prev, data])
8 }
9 }
10 );
11
12 return (
13 <>
14 {loading && <p>Loading...</p>}
15 {JSON.stringify(accumulatedData, undefined, 2)}
16 </>
17 );
18}⚠️ Note: The
useSubscriptionoptiononDatais available in Apollo Client >= 3.7. In previous versions, the equivalent option is namedonSubscriptionData.
Now, the first message will be added to the accumulatedData array since onData is called before the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with onData we can guarantee each message received after the component mounts is added to accumulatedData.
Example
1 const COMMENTS_SUBSCRIPTION = gql`
2 subscription OnCommentAdded($repoFullName: String!) {
3 commentAdded(repoFullName: $repoFullName) {
4 id
5 content
6 }
7 }
8 `;
9
10 function DontReadTheComments({ repoFullName }) {
11 const {
12 data: { commentAdded },
13 loading,
14 } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
15 return <h4>New comment: {!loading && commentAdded.content}</h4>;
16 }Signature
1useSubscription<TData, TVariables>(
2 subscription: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: SubscriptionHookOptions<NoInfer<TData>, NoInfer<TVariables>>
4): {
5 restart: () => void;
6 loading: boolean;
7 data?: TData | undefined;
8 error?: ApolloError;
9 variables?: TVariables | undefined;
10}Parameters
A GraphQL subscription document parsed into an AST by gql.
Options to control how the subscription is executed.
Show/hide child attributes
ApolloClient<object>An ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in.
DefaultContextShared context between your component and your network interface (Apollo Link).
ErrorPolicySpecifies the ErrorPolicy to be used for this operation
Record<string, any>Shared context between your component and your network interface (Apollo Link).
FetchPolicyHow you want your component to interact with the Apollo cache. For details, see Setting a fetch policy.
booleanIf true, the hook will not cause the component to rerender. This is useful when you want to control the rendering of your component yourself with logic in the onData and onError callbacks.
Changing this to true when the hook already has data will reset the data to undefined.
onComplete(optional)Requires ≥ 3.7.0
() => voidAllows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component completes the subscription.
onData(optional)Requires ≥ 3.7.0
(options: OnDataOptions<TData>) => anyAllows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component receives data. The callback options object param consists of the current Apollo Client instance in client, and the received subscription data in data.
onError(optional)Requires ≥ 3.7.0
(error: ApolloError) => voidAllows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component receives an error.
boolean | ((options: BaseSubscriptionOptions<TData, TVariables>) => boolean)Determines if your subscription should be unsubscribed and subscribed again when an input to the hook (such as subscription or variables) changes.
booleanDetermines if the current subscription should be skipped. Useful if, for example, variables depend on previous queries and are not ready yet.
TVariablesAn object containing all of the variables your subscription needs to execute
() => void⚠️ Deprecated
Use
onCompleteinstead
Allows the registration of a callback function that will be triggered when the useSubscription Hook / Subscription component completes the subscription.
(options: OnSubscriptionDataOptions<TData>) => any⚠️ Deprecated
Use
onDatainstead
Allows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component receives data. The callback options object param consists of the current Apollo Client instance in client, and the received subscription data in subscriptionData.
Result
Query result object{
restart: () => void;
loading: boolean;
data?: TData | undefined;
error?: ApolloError;
variables?: TVariables | undefined;
}useApolloClientRequires ≥ 3.0.0
Example
1 import { useApolloClient } from '@apollo/client';
2
3 function SomeComponent() {
4 const client = useApolloClient();
5 // `client` is now set to the `ApolloClient` instance being used by the
6 // application (that was configured using something like `ApolloProvider`)
7 }Signature
1useApolloClient(
2 override?: ApolloClient<object>
3): ApolloClient<object>Parameters
Result
The `ApolloClient` instance being used by the application.ApolloClient<object>useReactiveVarRequires ≥ 3.2.0
Reads the value of a reactive variable and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes without relying on the useQuery hook.
Example
1 import { makeVar, useReactiveVar } from "@apollo/client";
2 export const cartItemsVar = makeVar([]);
3
4 export function Cart() {
5 const cartItems = useReactiveVar(cartItemsVar);
6 // ...
7 }Signature
1useReactiveVar<T>(
2 rv: ReactiveVar<T>
3): TParameters
Result
The current value of the reactive variable.TuseFragmentRequires ≥ 3.8.0
useFragment represents a lightweight live binding into the Apollo Client Cache and enables Apollo Client to broadcast very specific fragment results to individual components. 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 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.
Note: this hook was introduced in
3.7.0as experimental but stabilized in3.8.0. In3.7.xand3.8.0-alpha.xreleases, this hook is exported asuseFragment_experimental. Starting with3.8.0-beta.0and greater the_experimentalsuffix was removed in its named export.
Example
To view a useFragment example, see the Fragments page.
Function Signature
1function useFragment<
2 TData = any,
3 TVars = OperationVariables
4>({
5 from: string | StoreObject | Reference;
6 fragment: DocumentNode | TypedDocumentNode<TData, TVars>;
7 fragmentName?: string;
8 optimistic?: boolean;
9 variables?: TVars;
10 returnPartialData?: boolean;
11}): UseFragmentResult<TData> {}Params
options
| Name / Type |
Description |
|---|---|
| Operation options | |
| 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). |
| Required. A GraphQL fragment document parsed into an AST with the gql template literal. |
| 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. |
| If true, readFragment returns optimistic results.The default value is true. |
| 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. |
| ⚠️ Deprecated:
Using 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 | |
| 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). |
| 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. |
| 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. |
useSuspenseQueryRequires ≥ 3.8.0
For a detailed explanation of useSuspenseQuery, see the fetching with Suspense reference.
Example
1import { Suspense } from 'react';
2import { useSuspenseQuery } from '@apollo/client';
3
4const listQuery = gql`
5 query {
6 list {
7 id
8 }
9 }
10`;
11
12function App() {
13 return (
14 <Suspense fallback={<Spinner />}>
15 <List />
16 </Suspense>
17 );
18}
19
20function List() {
21 const { data } = useSuspenseQuery(listQuery);
22
23 return (
24 <ol>
25 {data.list.map(item => <Item key={item.id} id={item.id}/>)}
26 </ol>
27 );
28}
29Signature
1function useSuspenseQuery<TData, TVariables>(
2 query: DocumentNode,
3 options?: SuspenseQueryHookOptions<TData, TVariables> | SkipToken,
4): UseSuspenseQueryResult<TData, TVariables>Params
query
| Param | Type | Description |
|---|---|---|
query | (Typed)DocumentNode | A GraphQL query document parsed into an AST by gql. |
options
Instead of passing a SuspenseQueryHookOptions object into the hook, you can also pass a skipToken to prevent the useSuspenseQuery hook from executing the query or suspending.
TVariablesAn 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.
ErrorPolicySpecifies 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, meaning that the query result includes error details but not partial results.
boolean⚠️ Deprecated
We recommend using
skipTokenin place of theskipoption as it is more type-safe.This option is deprecated and only supported to ease the migration from useQuery. It will be removed in a future release.
If true, the query is not executed. The default value is false.
Recommended usage of skipToken:
1import { skipToken, useSuspenseQuery } from '@apollo/client';
2
3const { data } = useSuspenseQuery(query, id ? { variables: { id } } : skipToken);ApolloClient<any>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.
string | number | any[]A unique identifier for the query. Each item in the array must be a stable identifier to prevent infinite fetches.
This is useful when using the same query and variables combination in more than one component, otherwise the components may clobber each other. This can also be used to force the query to re-evaluate fresh.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
SuspenseQueryHookFetchPolicySpecifies 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.
The default value is cache-first.
RefetchWritePolicyWatched queries must opt into overwriting existing data on refetch, by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.
The default value is "overwrite".
booleanIf 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.
boolean⚠️ Deprecated
Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option.canonizeResultswill be removed in Apollo Client 4.0.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
Result
| Name / Type |
Description |
| Operation result | |
| 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). |
| 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. |
| 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 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. |
| 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. |
| 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. |
useBackgroundQueryRequires ≥ 3.8.0
For a detailed explanation of useBackgroundQuery, see the fetching with Suspense reference.
Example
1import { Suspense } from 'react';
2import {
3 ApolloClient,
4 InMemoryCache,
5 useBackgroundQuery,
6 useReadQuery,
7} from '@apollo/client';
8
9const query = gql`
10 foo {
11 bar
12 }
13`;
14
15const client = new ApolloClient({
16 uri: "http://localhost:4000/graphql",
17 cache: new InMemoryCache()
18});
19
20function SuspenseFallback() {
21 return <div>Loading...</div>;
22}
23
24function Child({ queryRef }) {
25 const { data } = useReadQuery(queryRef);
26
27 return <div>{data.foo.bar}</div>;
28}
29
30function Parent() {
31 const [queryRef] = useBackgroundQuery(query);
32
33 return (
34 <Suspense fallback={<SuspenseFallback />}>
35 <Child queryRef={queryRef} />
36 </Suspense>
37 );
38}
39
40function App() {
41 return (
42 <ApolloProvider client={client}>
43 <Parent />
44 </ApolloProvider>
45 );
46}Signature
1function useBackgroundQuery<TData, TVariables>(
2 query: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options: BackgroundQueryHookOptions<TData, TVariables> | SkipToken,
4): [
5 // Will return `undefined` here if no query has been executed yet and the query
6 // is currently skipped using `skipToken` or { skip: true }
7 QueryRef<TData> | undefined,
8 {
9 fetchMore: FetchMoreFunction<TData, TVariables>;
10 refetch: RefetchFunction<TData, TVariables>;
11 }
12]Params
query
| Param | Type | Description |
|---|---|---|
query | (Typed)DocumentNode | A GraphQL query document parsed into an AST by gql. |
options
Instead of passing a BackgroundQueryHookOptions object into the hook, you can also pass a skipToken to prevent the useBackgroundQuery hook from executing the query.
If no query has been executed yet and you skip the query, the hook will return undefined instead of a queryRef.
| 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 none, which causes the useReadQuery hook to throw the error. |
| Networking options | |
| If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain. |
| ⚠️ Deprecated:
Using 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. |
| 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 | |
| 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. |
| 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. |
| Watched queries must opt into overwriting existing data on refetch, by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.The default value is "overwrite". |
| If true, the query is not executed. The default value is false.This option is deprecated and only supported to ease the migration from useQuery. It will be removed in a future release.
Please use skipToken instead of the skip option as it is more type-safe. |
Result
| Name / Type |
Description |
| Query reference | |
| 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 | |
| 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. |
| 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. |
useReadQueryRequires ≥ 3.8.0
For a detailed explanation of useReadQuery, see the fetching with Suspense reference.
Example
See the example in the useBackgroundQuery section above.
Signature
1function useReadQuery<TData>(
2 queryRef: QueryRef<TData>
3): {
4 data: TData;
5 networkStatus: NetworkStatus;
6 error: ApolloError | undefined;
7} {}Params
queryRef
| Param | Type | Description |
|---|---|---|
queryRef | QueryRef | 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 undefined if a query results in one or more errors (depending on the query's errorPolicy). |
| 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. |
| A number indicating the current network state of the query's associated request. See possible values. |
useLoadableQueryRequires ≥ 3.9.0
A hook for imperatively loading a query, such as responding to a user interaction.
Refer to the Suspense - Fetching in response to user interaction section for a more in-depth overview of
useLoadableQuery.
Example
1 import { gql, useLoadableQuery } from "@apollo/client";
2
3 const GET_GREETING = gql`
4 query GetGreeting($language: String!) {
5 greeting(language: $language) {
6 message
7 }
8 }
9 `;
10
11 function App() {
12 const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);
13
14 return (
15 <>
16 <button onClick={() => loadGreeting({ language: "english" })}>
17 Load greeting
18 </button>
19 <Suspense fallback={<div>Loading...</div>}>
20 {queryRef && <Hello queryRef={queryRef} />}
21 </Suspense>
22 </>
23 );
24 }
25
26 function Hello({ queryRef }) {
27 const { data } = useReadQuery(queryRef);
28
29 return <div>{data.greeting.message}</div>;
30 }Signature
1useLoadableQuery<TData, TVariables>(
2 query: DocumentNode | TypedDocumentNode<TData, TVariables>,
3 options?: LoadableQueryHookOptions
4): UseLoadableQueryResult<TData, TVariables>Parameters
A GraphQL query document parsed into an AST by gql.
Options to control how the query is executed.
Show/hide child attributes
ApolloClient<any>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.
ErrorPolicySpecifies 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, meaning that the query result includes error details but not partial results.
string | number | any[]A unique identifier for the query. Each item in the array must be a stable identifier to prevent infinite fetches.
This is useful when using the same query and variables combination in more than one component, otherwise the components may clobber each other. This can also be used to force the query to re-evaluate fresh.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
LoadableQueryHookFetchPolicySpecifies 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.
The default value is cache-first.
RefetchWritePolicySpecifies whether a NetworkStatus.refetch operation should merge incoming field data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with Apollo Client 3.x.
booleanIf 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.
boolean⚠️ Deprecated
Using
canonizeResultscan result in memory leaks so we generally do not recommend using this option.canonizeResultswill be removed in Apollo Client 4.0.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
Result
1[
2 loadQuery: LoadQueryFunction<TVariables>,
3 queryRef: QueryRef<TData, TVariables> | null,
4 {
5 fetchMore: FetchMoreFunction<TData, TVariables>;
6 refetch: RefetchFunction<TData, TVariables>;
7 reset: ResetFunction;
8 }
9]loadQueryLoadQueryFunction<TVariables>queryRef returned by useLoadableQuery, which should be passed to useReadQuery.queryRefQueryRef<TData, TVariables> | nullqueryRef used by useReadQuery to read the query result.Show/hide child attributes
handlers{ fetchMore: FetchMoreFunction<TData, TVariables>; refetch: RefetchFunction<TData, TVariables>; reset: ResetFunction; }refetch.useQueryRefHandlersRequires ≥ 3.9.0
A React hook that returns a refetch and fetchMore function for a given queryRef.
This is useful to get access to handlers for a queryRef that was created by createQueryPreloader or when the handlers for a queryRef produced in a different component are inaccessible.
Example
1 const MyComponent({ queryRef }) {
2 const { refetch, fetchMore } = useQueryRefHandlers(queryRef);
3
4 // ...
5 }Signature
1useQueryRefHandlers<TData, TVariables>(
2 queryRef: QueryRef<TData, TVariables>
3): UseQueryRefHandlersResult<TData, TVariables>Parameters
A QueryRef returned from useBackgroundQuery, useLoadableQuery, or createQueryPreloader.
Show/hide child attributes
Result
UseQueryRefHandlersResult<TData, TVariables>skipTokenRequires ≥ 3.8.0
While not a hook by itself, skipToken is designed to be used with useSuspenseQuery and useBackgroundQuery.
If a skipToken is passed into one of those hooks instead of the options object, that hook will not cause any requests or suspenseful behavior, while keeping the last data available.
1import { skipToken, useSuspenseQuery } from '@apollo/client';
2const { data } = useSuspenseQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);1import { skipToken, useBackgroundQuery } from '@apollo/client';
2const [queryRef] = useBackgroundQuery(
3 query,
4 id ? { variables: { id } } : skipToken
5);Note: Why do we recommendskipTokenover{ skip: true }?Imagine this very common scenario forskip: You want to skip your query if a certain variable is not set. You might be tempted to write something like this:But in that case, TypeScript will complain:TypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id }, 3 skip: !id 4});To get around that, you have to tell TypeScript to ignore the fact thatText1Type 'number | undefined' is not assignable to type 'number'. 2 Type 'undefined' is not assignable to type 'number'.ts(2769)idcould beundefined:Alternatively, you could also use some obscure default value:TypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id: id! }, 3 skip: !id 4});What both of these solutions have in common: They hide a potential bug. If yourTypeScript1const { data } = useSuspenseQuery(query, { 2 variables: { id: id || 0 }, 3 skip: !id 4});skiplogic becomes more complex in the future, you might accidentally introduce a bug that causes your query not to be skipped, even thoughidis stillundefined- and TypeScript won't be able to warn you about it.So instead, we recommend usingskipToken, as that will work without a lie to the compiler or an obscure default value:In this case, it becomes apparent for TypeScript that there is a direct connection between skipping and theTypeScript1const { data } = useSuspenseQuery( 2 query, 3 id ? { variables: { id } } : skipToken 4);variablesoption - and it will work without unsafe workarounds.