Hooks
Apollo Client react hooks API reference
Installation
Apollo Client >= 3 includes React hooks functionality out of the box. You don't need to install any additional packages.
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.
import { ApolloProvider } from '@apollo/client';
Props
Option | Type | Description |
---|---|---|
client | ApolloClient<TCache> | An ApolloClient instance. |
Example
const client = new ApolloClient({cache: new InMemoryCache(),uri: "http://localhost:4000/graphql"});ReactDOM.render(<ApolloProvider client={client}><MyRootComponent /></ApolloProvider>,document.getElementById('root'),);
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
import { ApolloConsumer } from '@apollo/client';function WithApolloClient() {return (<ApolloConsumer>{client => 'We have access to the client!' /* do stuff here */}</ApolloConsumer>);}
useQuery
Example
import { gql, useQuery } from '@apollo/client';const GET_GREETING = gql`query GetGreeting($language: String!) {greeting(language: $language) {message}}`;function Hello() {const { loading, error, data } = useQuery(GET_GREETING, {variables: { language: 'english' },});if (loading) return <p>Loading ...</p>;return <h1>Hello {data.greeting.message}!</h1>;}
Refer to the Queries section for a more in-depth overview of useQuery
.
Signature
function useQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode,options?: QueryHookOptions<TData, TVariables>,): QueryResult<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 | |
| A GraphQL query string parsed into an AST with the Optional for the |
| 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 |
| A callback function that's called when your query successfully completes with zero errors (or if This function is passed the query's result |
| A callback function that's called when the query encounters one or more errors (unless This function is passed an |
| If This property is part of Apollo Client's React integration, and it is not available in the core The default value is |
Networking options | |
| Specifies the interval (in milliseconds) at which the query polls for updated results. The default value is |
| If The default value is |
| If you're using Apollo Link, this object is the initial value of the |
| Pass |
| 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. The default value is |
| Specifies the For example, you can use this to switch back to a |
| If The default value is |
Deprecated options | |
| Deprecated. If The default value is |
Result
Name / Type | Description |
---|---|
Operation data | |
| An object containing the result of your GraphQL query after it completes. This value might be |
| An object containing the result from the most recent previous execution of this query. This value is |
| If the query produces one or more errors, this object contains either an array of For more information, see Handling operation errors. |
| An object containing the variables that were provided for the query. |
Network info | |
| If |
| A number indicating the current network state of the query's associated request. See possible values. Used in conjunction with the |
| The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache. |
| If This field is only present on the result object returned by |
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 See also Refetching. |
| A function that helps you fetch the next set of results for a paginated list field. |
| A function that instructs the query to begin re-executing at a specified interval (in milliseconds). |
| A function that instructs the query to stop polling after a previous call to |
| 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. |
| A 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. |
useLazyQuery
Example
import { gql, useLazyQuery } from "@apollo/client";const GET_GREETING = gql`query GetGreeting($language: String!) {greeting(language: $language) {message}}`;function Hello() {const [loadGreeting, { called, loading, data }] = useLazyQuery(GET_GREETING,{ variables: { language: "english" } });if (called && loading) return <p>Loading ...</p>if (!called) {return <button onClick={() => loadGreeting()}>Load greeting</button>}return <h1>Hello {data.greeting.message}!</h1>;}
Refer to the Queries section for a more in-depth overview of useLazyQuery
.
Signature
function useLazyQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode,options?: LazyQueryHookOptions<TData, TVariables>,): [(options?: LazyQueryHookOptions<TData, TVariables>) => Promise<LazyQueryResult<TData, TVariables>>,LazyQueryResult<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 | |
| A GraphQL query string parsed into an AST with the Optional for the |
| 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 |
| A callback function that's called when your query successfully completes with zero errors (or if This function is passed the query's result |
| A callback function that's called when the query encounters one or more errors (unless This function is passed an |
| If This property is part of Apollo Client's React integration, and it is not available in the core The default value is |
Networking options | |
| Specifies the interval (in milliseconds) at which the query polls for updated results. The default value is |
| If The default value is |
| If you're using Apollo Link, this object is the initial value of the |
| Pass |
| 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. The default value is |
| Specifies the For example, you can use this to switch back to a |
| If The default value is |
Deprecated options | |
| Deprecated. If The default value is |
Result tuple
Execute function (first tuple item)
Param | Type | Description |
---|---|---|
Execute function | (options?: LazyQueryHookOptions<TVariables>) => Promise<LazyQueryResult<TData, TVariables>> | Function that can be triggered to execute the suspended query. After being called, useLazyQuery behaves just like useQuery . The useLazyQuery function returns a promise that fulfills with a query result when the query succeeds or fails. |
LazyQueryResult<TData, TVariables>
object (second tuple item)
Name / Type | Description |
---|---|
Operation data | |
| An object containing the result of your GraphQL query after it completes. This value might be |
| An object containing the result from the most recent previous execution of this query. This value is |
| If the query produces one or more errors, this object contains either an array of For more information, see Handling operation errors. |
| An object containing the variables that were provided for the query. |
Network info | |
| If |
| A number indicating the current network state of the query's associated request. See possible values. Used in conjunction with the |
| The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache. |
| If This field is only present on the result object returned by |
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 See also Refetching. |
| A function that helps you fetch the next set of results for a paginated list field. |
| A function that instructs the query to begin re-executing at a specified interval (in milliseconds). |
| A function that instructs the query to stop polling after a previous call to |
| 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. |
| A 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. |
useMutation
Example
import { gql, useMutation } from '@apollo/client';const ADD_TODO = gql`mutation AddTodo($type: String!) {addTodo(type: $type) {idtype}}`;function AddTodo() {let input;const [addTodo, { data }] = useMutation(ADD_TODO);return (<div><formonSubmit={e => {e.preventDefault();addTodo({ variables: { type: input.value } });input.value = '';}}><inputref={node => {input = node;}}/><button type="submit">Add Todo</button></form></div>);}
Refer to the Mutations section for a more in-depth overview of useMutation
.
Signature
function useMutation<TData = any, TVariables = OperationVariables>(mutation: DocumentNode,options?: MutationHookOptions<TData, TVariables>,): MutationTuple<TData, TVariables> {}
Params
mutation
Param | Type | Description |
---|---|---|
mutation | DocumentNode | A GraphQL mutation document parsed into an AST by gql . |
options
Name / Type | Description |
---|---|
Operation options | |
| A GraphQL query string parsed into an AST with the Optional for the Required for the |
| An 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. |
| Specifies how the mutation handles a response that returns both GraphQL errors and partial results. For details, see GraphQL error policies. The default value is |
| A callback function that's called when your mutation successfully completes with zero errors (or if This function is passed the mutation's result |
| A callback function that's called when the mutation encounters one or more errors (unless This function is passed an |
| Optional callback for intercepting queries whose cache data has been updated by the mutation, as well as any queries specified in the Returning a |
| An 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:
|
| If The default value is |
| If The default value is |
Networking options | |
| 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. |
| If you're using Apollo Link, this object is the initial value of the |
Caching options | |
| A function used to update the Apollo Client cache after the mutation completes. For more information, see Updating the cache after a mutation. |
| If provided, 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. |
| Provide The default value is Unlike queries, mutations do not support fetch policies besides |
MutationTuple<TData, TVariables>
result tuple
Mutate function:
Name / Type | Description |
---|---|
| A function to trigger the mutation from your UI. You can optionally pass this function any of the following options:
Any option you pass here overrides any existing value for that option that you passed to The mutate function returns a promise that fulfills with your mutation result. |
Mutation result:
Name / Type | Description |
---|---|
| The data returned from your mutation. Can be |
| If |
| If the mutation produces one or more errors, this object contains either an array of For more information, see Handling operation errors. |
| If |
| The instance of Apollo Client that executed the mutation. Can be useful for manually executing followup operations or writing data to the cache. |
| A function that you can call to reset the mutation's result to its initial, uncalled state. |
useSubscription
Example
const COMMENTS_SUBSCRIPTION = gql`subscription OnCommentAdded($repoFullName: String!) {commentAdded(repoFullName: $repoFullName) {idcontent}}`;function DontReadTheComments({ repoFullName }) {const {data: { commentAdded },loading,} = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });return <h4>New comment: {!loading && commentAdded.content}</h4>;}
Refer to the Subscriptions section for a more in-depth overview of useSubscription
.
Subscriptions and React 18 Automatic Batching
With React 18's automatic batching, multiple state updates may be grouped into a single re-render for better performance.
If your subscription API sends multiple messages at the same time or in very fast succession (within fractions of a millisecond), it is likely that only the last message received in that narrow time frame will result in a re-render.
Consider the following component:
export function Subscriptions() {const { data, error, loading } = useSubscription(query);const [accumulatedData, setAccumulatedData] = useState([]);useEffect(() => {setAccumulatedData((prev) => [...prev, data]);}, [data]);return (<>{loading && <p>Loading...</p>}{JSON.stringify(accumulatedData, undefined, 2)}</>);}
If your subscription back-end emits two messages with the same timestamp, only the last message received by Apollo Client will be rendered. This is because React 18 will batch these two state updates into a single re-render.
Since the component above is using useEffect
to push data
into a piece of local state on each Subscriptions
re-render, the first message will never be added to the accumulatedData
array since its render was skipped.
Instead of using useEffect
here, we can re-write this component to use the onData
callback function accepted in useSubscription
's options
object:
export function Subscriptions() {const [accumulatedData, setAccumulatedData] = useState([]);const { data, error, loading } = useSubscription(query,{onData({ data }) {setAccumulatedData((prev) => [...prev, data])}});return (<>{loading && <p>Loading...</p>}{JSON.stringify(accumulatedData, undefined, 2)}</>);}
⚠️ Note: The useSubscription
option onData
is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named onSubscriptionData
.
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
.
Signature
function useSubscription<TData = any, TVariables = OperationVariables>(subscription: DocumentNode,options?: SubscriptionHookOptions<TData, TVariables>,): {variables: TVariables;loading: boolean;data?: TData;error?: ApolloError;} {}
Params
subscription
Param | Type | Description |
---|---|---|
subscription | DocumentNode | A GraphQL subscription document parsed into an AST by gql . |
options
Option | Type | Description |
---|---|---|
subscription | DocumentNode | A GraphQL subscription document parsed into an AST by graphql-tag . Optional for the useSubscription Hook since the subscription can be passed in as the first parameter to the Hook. Required for the Subscription component. |
variables | { [key: string]: any } | An object containing all of the variables your subscription needs to execute |
shouldResubscribe | boolean | Determines if your subscription should be unsubscribed and subscribed again when an input to the hook (such as subscription or variables ) changes. |
skip | boolean | Determines if the current subscription should be skipped. Useful if, for example, variables depend on previous queries and are not ready yet. |
onSubscriptionData | Deprecated. (options: OnSubscriptionDataOptions<TData>) => any | 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 . |
onData | (options: OnDataOptions<TData>) => any | 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 data . |
onError | (error: ApolloError) => void | Allows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component receives an error. |
onSubscriptionComplete | Deprecated. () => void | Allows the registration of a callback function that will be triggered when the useSubscription Hook / Subscription component completes the subscription. |
onComplete | () => void | Allows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component completes the subscription. |
fetchPolicy | FetchPolicy | How you want your component to interact with the Apollo cache. For details, see Setting a fetch policy. |
context | Record<string, any> | Shared context between your component and your network interface (Apollo Link). |
client | ApolloClient | An ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in. |
Result
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL subscription. Defaults to an empty object. |
loading | boolean | A boolean that indicates whether any initial data has been returned |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
useApolloClient
Example
import { useApolloClient } from '@apollo/client';function SomeComponent() {const client = useApolloClient();// `client` is now set to the `ApolloClient` instance being used by the// application (that was configured using something like `ApolloProvider`)}
Signature
function useApolloClient(): ApolloClient<object> {}
Result
Param | Type | Description |
---|---|---|
Apollo Client instance | ApolloClient<object> | The ApolloClient instance being used by the application. |
useReactiveVar
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
import { makeVar, useReactiveVar } from "@apollo/client";export const cartItemsVar = makeVar([]);export function Cart() {const cartItems = useReactiveVar(cartItemsVar);// ...
Signature
function useReactiveVar<T>(rv: ReactiveVar<T>): T {}
useFragment
Since 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.0
as experimental but stabilized in 3.8.0
. In 3.7.x
and 3.8.0-alpha.x
releases, this hook is exported as useFragment_experimental
. Starting with 3.8.0-beta.0
and greater the _experimental
suffix was removed in its named export.
Example
To view a useFragment
example, see the Fragments page.
Function Signature
function useFragment<TData = any,TVars = OperationVariables>({from: string | StoreObject | Reference;fragment: DocumentNode | TypedDocumentNode<TData, TVars>;fragmentName?: string;optimistic?: boolean;variables?: TVars;returnPartialData?: boolean;canonizeResults?: boolean;}): UseFragmentResult<TData> {}
Params
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
Since 3.8.0
For a detailed explanation of useSuspenseQuery
, see the fetching with Suspense reference.
Example
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>);}
Signature
function useSuspenseQuery<TData, TVariables>(query: DocumentNode,options?: SuspenseQueryHookOptions<TData, TVariables> | SkipToken,): 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.
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. |
| 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. |
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 |
| If This option is deprecated and only supported to ease the migration from |
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. |
useBackgroundQuery
Since 3.8.0
For a detailed explanation of useBackgroundQuery
, see the fetching with Suspense reference.
Example
import { Suspense } from 'react';import {ApolloClient,InMemoryCache,useBackgroundQuery,useReadQuery,} from '@apollo/client';const query = gql`foo {bar}`;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}><Parent /></ApolloProvider>);}
Signature
function useBackgroundQuery<TData, TVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>,options: BackgroundQueryHookOptions<TData, TVariables> | SkipToken,): [// Will return `undefined` here if no query has been executed yet and the query// is currently skipped using `skipToken` or { skip: true }QueryReference<TData> | undefined,{fetchMore: FetchMoreFunction<TData, TVariables>;refetch: RefetchFunction<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 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 |
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 |
| If This option is deprecated and only supported to ease the migration from |
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
Since 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
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. |
skipToken
Since 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.
import { skipToken, useSuspenseQuery } from '@apollo/client';const { data } = useSuspenseQuery(query,id ? { variables: { id } } : skipToken);
import { skipToken, useBackgroundQuery } from '@apollo/client';const [queryRef] = useBackgroundQuery(query,id ? { variables: { id } } : skipToken);
Note: Why do we recommend skipToken
over { skip: true }
?
Imagine this very common scenario for skip
: You want to skip your query if a certain variable is not set. You might be tempted to write something like this:
const { data } = useSuspenseQuery(query, {variables: { id },skip: !id});
But in that case, TypeScript will complain:
Type 'number | undefined' is not assignable to type 'number'.Type 'undefined' is not assignable to type 'number'.ts(2769)
To get around that, you have to tell TypeScript to ignore the fact that id
could be undefined
:
const { data } = useSuspenseQuery(query, {variables: { id: id! },skip: !id});
Alternatively, you could also use some obscure default value:
const { data } = useSuspenseQuery(query, {variables: { id: id || 0 },skip: !id});
What both of these solutions have in common: They hide a potential bug. If your skip
logic becomes more complex in the future, you might accidentally introduce a bug that causes your query not to be skipped, even though id
is still undefined
- and TypeScript won't be able to warn you about it.
So instead, we recommend using skipToken
, as that will work without a lie to the compiler or an obscure default value:
const { data } = useSuspenseQuery(query,id ? { variables: { id } } : skipToken);
In this case, it becomes apparent for TypeScript that there is a direct connection between skipping and the variables
option - and it will work without unsafe workarounds.