Docs
Launch GraphOS Studio
Since 3.0.0

Hooks

Apollo Client react hooks API reference


The ApolloProvider component

The ApolloProvider component leverages React's Context API to make a configured instance available throughout a React component tree. This component can be imported directly from the @apollo/client package.

import { ApolloProvider } from '@apollo/client';

Props

OptionTypeDescription
clientApolloClient<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 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 . 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
Since 3.0.0

A hook for executing queries in an Apollo application.

To run a within a React component, call useQuery and pass it a .

When your component renders, useQuery returns an object from 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

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>;
}

Signature

function useQuery<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
): QueryResult<TData, TVariables>

(src/react/hooks/useQuery.ts)

Parameters

Name / Type
Description

query

DocumentNode | TypedDocumentNode<TData, TVariables>

A parsed into an AST by gql.

options (optional)

QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>

Options to control how the is executed.

Show/hide child attributes
Operation options

client (optional)

ApolloClient<any>

The instance of ApolloClient to use to execute the .

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

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

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

(data: NoInfer<TData>) => void

A callback function that's called when your successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).

This function is passed the 's result data.

(error: ApolloError) => void

A callback function that's called when the 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 is not executed.

The default value is false.

NoInfer<TVariables>

An object containing all of the your requires to execute.

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

Networking options
DefaultContext

If 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 's associated component re-renders whenever the network status changes or a network error occurs.

The default value is false.

Specifies the interval (in milliseconds) at which the polls for updated results.

The default value is 0 (no polling).

A 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.

Pass false to skip executing the during server-side rendering.

Caching options
WatchQueryFetchPolicy

Specifies how the interacts with the 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

Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchFetchPolicy to revert back to whenever change (unless nextFetchPolicy intervenes).

WatchQueryFetchPolicy | ((this: WatchQueryOptions<NoInfer<TVariables>, NoInfer<TData>>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<NoInfer<TData>, NoInfer<TVariables>>) => WatchQueryFetchPolicy)

Specifies the FetchPolicy to be used after this has completed.

Specifies whether a NetworkStatus.refetch should merge incoming data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with 3.x.

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

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.

⚠️ Deprecated

Setting this option is unnecessary in 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

If true, causes a refetch if the query result is detected as partial.

The default value is false.

Result

Query result object
QueryResult<TData, TVariables>
Show/hide child attributes
Operation data
TData | undefined

An object containing the result of your after it completes.

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

ApolloError

If the 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.

An object containing the result from the most recent previous execution of this .

This value is undefined if this is the 's first execution.

TVariables | undefined

An object containing the that were provided for the .

Network info
boolean

If true, the associated lazy has been executed.

This is only present on the result object returned by useLazyQuery.

ApolloClient<any>

The instance of that executed the . Can be useful for manually executing followup queries or writing data to the cache.

boolean

If true, the is still in flight and results have not yet been returned.

NetworkStatus

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

Used in conjunction with the notifyOnNetworkStatusChange option.

Helper functions
<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & { updateQuery?: (previousQueryResult: TData, options: { fetchMoreResult: TFetchData; variables: TFetchVars; }) => TData; }) => Promise<ApolloQueryResult<TFetchData>>

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

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

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

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

See also Refetching.

(pollInterval: number) => void

A function that instructs the to begin re-executing at a specified interval (in milliseconds).

() => void

A function that instructs the to stop polling after a previous call to startPolling.

<TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData>) => () => void

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

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

<TVars extends OperationVariables = TVariables>(mapFn: (previousQueryResult: TData, options: Pick<WatchQueryOptions<TVars, TData>, "variables">) => TData) => void

A function that enables you to update the 's cached result without executing a followup .

See using updateQuery and updateFragment for additional information.

Other
ObservableQuery<TData, TVariables>

A reference to the internal ObservableQuery used by the hook.

useLazyQuery
Since 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

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>;
}

Signature

function useLazyQuery<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: LazyQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>
): LazyQueryResultTuple<TData, TVariables>

(src/react/hooks/useLazyQuery.ts)

Parameters

Name / Type
Description

query

DocumentNode | TypedDocumentNode<TData, TVariables>

A parsed into an AST by gql.

options (optional)

LazyQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>

Default options to control how the is executed.

Show/hide child attributes
Operation options
ApolloClient<any>

The instance of ApolloClient to use to execute the .

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

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

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

(data: NoInfer<TData>) => void

A callback function that's called when your successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).

This function is passed the 's result data.

(error: ApolloError) => void

A callback function that's called when the 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.

NoInfer<TVariables>

An object containing all of the your requires to execute.

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

Networking options
DefaultContext

If 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 's associated component re-renders whenever the network status changes or a network error occurs.

The default value is false.

Specifies the interval (in milliseconds) at which the polls for updated results.

The default value is 0 (no polling).

A 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.

Pass false to skip executing the during server-side rendering.

Caching options
WatchQueryFetchPolicy

Specifies how the interacts with the 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

Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchFetchPolicy to revert back to whenever change (unless nextFetchPolicy intervenes).

WatchQueryFetchPolicy | ((this: WatchQueryOptions<NoInfer<TVariables>, NoInfer<TData>>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<NoInfer<TData>, NoInfer<TVariables>>) => WatchQueryFetchPolicy)

Specifies the FetchPolicy to be used after this has completed.

Specifies whether a NetworkStatus.refetch should merge incoming data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with 3.x.

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

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.

⚠️ Deprecated

Setting this option is unnecessary in 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

If true, causes a refetch if the query result is detected as partial.

The default value is false.

Result

[execute: LazyQueryExecFunction<TData, TVariables>, result: QueryResult<TData, TVariables>]

A tuple of two values:

NameTypeDescription
execute(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.
resultQueryResult<TData, TVariables>The result of the query. See the `useQuery` hook for more details.
Show/hide child attributes
Operation data
TData | undefined

An object containing the result of your after it completes.

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

ApolloError

If the 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.

An object containing the result from the most recent previous execution of this .

This value is undefined if this is the 's first execution.

TVariables | undefined

An object containing the that were provided for the .

Network info
boolean

If true, the associated lazy has been executed.

This is only present on the result object returned by useLazyQuery.

ApolloClient<any>

The instance of that executed the . Can be useful for manually executing followup queries or writing data to the cache.

boolean

If true, the is still in flight and results have not yet been returned.

NetworkStatus

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

Used in conjunction with the notifyOnNetworkStatusChange option.

Helper functions
<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & { updateQuery?: (previousQueryResult: TData, options: { fetchMoreResult: TFetchData; variables: TFetchVars; }) => TData; }) => Promise<ApolloQueryResult<TFetchData>>

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

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

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

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

See also Refetching.

(pollInterval: number) => void

A function that instructs the to begin re-executing at a specified interval (in milliseconds).

() => void

A function that instructs the to stop polling after a previous call to startPolling.

<TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData>) => () => void

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

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

<TVars extends OperationVariables = TVariables>(mapFn: (previousQueryResult: TData, options: Pick<WatchQueryOptions<TVars, TData>, "variables">) => TData) => void

A function that enables you to update the 's cached result without executing a followup .

See using updateQuery and updateFragment for additional information.

Other
ObservableQuery<TData, TVariables>

A reference to the internal ObservableQuery used by the hook.

useMutation
Since 3.0.0

Refer to the Mutations section for a more in-depth overview of useMutation.

Example

import { gql, useMutation } from '@apollo/client';
const ADD_TODO = gql`
mutation AddTodo($type: String!) {
addTodo(type: $type) {
id
type
}
}
`;
function AddTodo() {
let input;
const [addTodo, { data }] = useMutation(ADD_TODO);
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { type: input.value } });
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}

Signature

function useMutation<TData, TVariables, TContext, TCache>(
mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: MutationHookOptions<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>
): MutationTuple<TData, TVariables, TContext, TCache>

(src/react/hooks/useMutation.ts)

Parameters

Name / Type
Description

mutation

DocumentNode | TypedDocumentNode<TData, TVariables>

A parsed into an AST by gql.

options (optional)

MutationHookOptions<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>

Options to control how the is executed.

Show/hide child attributes
Operation options

If true, makes sure all queries included in refetchQueries are completed before the is considered complete.

The default value is false (queries are refetched asynchronously).

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

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

If true, the 's data property is not updated with the 's result.

The default value is false.

(data: NoInfer<TData>, clientOptions?: BaseMutationOptions) => void

A callback function that's called when your successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned).

This function is passed the 's result data and any options passed to the .

(error: ApolloError, clientOptions?: BaseMutationOptions) => void

A callback function that's called when the 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 .

OnQueryUpdated<any>

Optional callback for intercepting queries whose cache data has been updated by the , as well as any queries specified in the refetchQueries: [...] list passed to client.mutate.

Returning a Promise from onQueryUpdated will cause the final Promise to await the returned Promise. Returning false causes the to be ignored.

((result: FetchResult<NoInfer<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude

An array (or a function that returns an array) that specifies which queries you want to refetch after the occurs.

Each array value can be either:

  • An object containing the query to execute, along with any variables

  • A string indicating the of the to refetch

NoInfer<TVariables>

An object containing all of the your requires to execute.

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

Networking options
ApolloClient<object>

The instance of ApolloClient to use to execute the .

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 context object that's passed along your link chain.

If true, the in-progress 's associated component re-renders whenever the network status changes or a network error occurs.

The default value is false.

Caching options
MutationFetchPolicy

Provide no-cache if the 's result should not be written to the cache.

The default value is network-only (which means the result is written to the cache).

Unlike queries, do not support fetch policies besides network-only and no-cache.

NoInfer<TData> | ((vars: NoInfer<TVariables>, { IGNORE }: { IGNORE: IgnoreModifier; }) => NoInfer<TData>)

By providing either an object or a callback function that, when invoked after a , allows you to return optimistic data and optionally skip updates via the IGNORE sentinel object, caches this temporary (and potentially incorrect) response until the completes, enabling more responsive UI updates.

For more information, see Optimistic mutation results.

MutationUpdaterFunction<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>

A function used to update the cache after the completes.

For more information, see Updating the cache after a mutation.

Other

To avoid retaining sensitive information from root , v3.4+ automatically clears any ROOT_MUTATION from the cache after each finishes. If you need this information to remain in the cache, you can prevent the removal by passing keepRootFields: true to the . ROOT_MUTATION result data are also passed to the update function, so we recommend obtaining the results that way, rather than using this option, if possible.

MutationQueryReducersMap<NoInfer<TData>>

A MutationQueryReducersMap, which is map from names to 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

[
mutate: (options?: MutationFunctionOptions<TData, TVariables>) => Promise<FetchResult<TData>>,
result: MutationResult<TData>
]
A tuple of two values:
NameTypeDescription
mutate( options?: MutationFunctionOptions<TData, TVariables> ) => Promise<FetchResult<TData>>
A function to trigger the mutation from your UI. You can optionally pass this function any of the following options:
  • awaitRefetchQueries
  • context
  • fetchPolicy
  • onCompleted
  • onError
  • optimisticResponse
  • refetchQueries
  • onQueryUpdated
  • update
  • variables
  • client

Any option you pass here overrides any existing value for that option that you passed to useMutation.

The mutate function returns a promise that fulfills with your result.

resultMutationResult<TData>The result of the mutation.
Show/hide child attributes
Other
boolean

If true, the 's mutate function has been called.

ApolloClient<object>

The instance of that executed the .

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

TData | null

The data returned from your . Can be undefined if ignoreResults is true.

ApolloError

If the 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.

boolean

If true, the is currently in flight.

() => void

A function that you can call to reset the 's result to its initial, uncalled state.

useSubscription
Since 3.0.0

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 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 back-end emits two messages with the same timestamp, only the last message received by 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 >= 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.

Example

const COMMENTS_SUBSCRIPTION = gql`
subscription OnCommentAdded($repoFullName: String!) {
commentAdded(repoFullName: $repoFullName) {
id
content
}
}
`;
function DontReadTheComments({ repoFullName }) {
const {
data: { commentAdded },
loading,
} = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
return <h4>New comment: {!loading && commentAdded.content}</h4>;
}

Signature

function useSubscription<TData, TVariables>(
subscription: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: SubscriptionHookOptions<NoInfer<TData>, NoInfer<TVariables>>
): SubscriptionResult<TData, TVariables>

(src/react/hooks/useSubscription.ts)

Parameters

Name / Type
Description

subscription

DocumentNode | TypedDocumentNode<TData, TVariables>

A parsed into an AST by gql.

options (optional)

SubscriptionHookOptions<NoInfer<TData>, NoInfer<TVariables>>

Options to control how the is executed.

Show/hide child attributes
Other
ApolloClient<object>

An ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in.

DefaultContext

Shared context between your component and your network interface ().

How you want your component to interact with the Apollo cache. For details, see Setting a fetch policy.

() => void

Allows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component completes the .

(options: OnDataOptions<NoInfer<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 instance in client, and the received data in data.

(error: ApolloError) => void

Allows the registration of a callback function that will be triggered each time the useSubscription Hook / Subscription component receives an error.

boolean | ((options: BaseSubscriptionOptions<NoInfer<TData>, NoInfer<TVariables>>) => boolean)

Determines if your should be unsubscribed and subscribed again when an input to the hook (such as subscription or variables) changes.

Determines if the current should be skipped. Useful if, for example, depend on previous queries and are not ready yet.

NoInfer<TVariables>

An object containing all of the your needs to execute

⚠️ Deprecated

Use onComplete instead

Allows the registration of a callback function that will be triggered when the useSubscription Hook / Subscription component completes the .

(options: OnSubscriptionDataOptions<NoInfer<TData>>) => any

⚠️ Deprecated

Use onData instead

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 instance in client, and the received data in subscriptionData.

Result

Query result object
SubscriptionResult<TData, TVariables>
Show/hide child attributes
Other

An object containing the result of your . Defaults to an empty object.

ApolloError

A runtime error with graphQLErrors and networkError properties

boolean

A boolean that indicates whether any initial data has been returned

useApolloClient
Since 3.0.0

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(
override?: ApolloClient<object>
): ApolloClient<object>

(src/react/hooks/useApolloClient.ts)

Parameters

Name / Type
Description

override (optional)

ApolloClient<object>

Result

The `ApolloClient` instance being used by the application.
ApolloClient<object>

useReactiveVar
Since 3.2.0

Reads the value of a reactive variable and re-renders the containing component whenever that '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

(src/react/hooks/useReactiveVar.ts)

Parameters

Name / Type
Description

rv

ReactiveVar<T>

A reactive .

Show/hide child attributes
Other
( cache: ApolloCache<any> ) => this
( cache: ApolloCache<any> ) => boolean
( listener: ReactiveListener<T> ) => () => void

Result

The current value of the reactive variable.
T

useFragment
Since 3.8.0

useFragment represents a lightweight live binding into the Cache and enables Apollo Client to broadcast very specific 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 and populating data in the cache (see the API reference). As a result, the component reading the data via useFragment is still subscribed to all changes in the data, but receives updates only when that '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;
}): UseFragmentResult<TData> {}

Params

options

Name /
Type
Description

Operation options

from

string | StoreObject | Reference

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

fragment

DocumentNode

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

fragmentName

string

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

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

optimistic

boolean

If true, readFragment returns optimistic results.

The default value is true.

variables

{ [key: string]: any }

An object containing all of the your requires.

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

canonizeResults

boolean

⚠️ Deprecated: Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

The default value is false.

Result

Name /
Type
Description

Operation result

data

TData

An object containing the data for a given .

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

complete

boolean

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

missing

MissingTree

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

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

ParamTypeDescription
query(Typed)DocumentNodeA 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 or suspending.

Properties

Name / Type
Description

An object containing all of the your requires to execute.

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

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

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

⚠️ Deprecated

We recommend using skipToken in place of the skip option as it is more type-safe.

This option is deprecated and only supported to ease the migration from use. It will be removed in a future release.

If true, the is not executed. The default value is false.

Operation options
ApolloClient<any>

The instance of ApolloClient to use to execute the .

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 . Each item in the array must be a stable identifier to prevent infinite fetches.

This is useful when using the same and 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.

Networking options
DefaultContext

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

Caching options
SuspenseQueryHookFetchPolicy

Specifies how the interacts with the 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.

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

The default value is "overwrite".

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

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

data

TData

An object containing the result of your after it completes.

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

error

ApolloError

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

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

networkStatus

NetworkStatus

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

Client

client

ApolloClient

The instance of that executed the .

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

Helper functions

refetch

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

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

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

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

fetchMore

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

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

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

subscribeToMore

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

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

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

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

ParamTypeDescription
query(Typed)DocumentNodeA 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 .

If no has been executed yet and you skip the query, the hook will return undefined instead of a queryRef.

Name /
Type
Description

Operation options

variables

{ [key: string]: any }

An object containing all of the your requires to execute.

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

errorPolicy

ErrorPolicy

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

For details, see GraphQL error policies.

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

Networking options

context

Record<string, any>

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

canonizeResults

Boolean

⚠️ Deprecated: Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

The default value is false.

client

ApolloClient

The instance of ApolloClient to use to execute the .

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

Caching options

fetchPolicy

SuspenseQueryHookFetchPolicy

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

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

The default value is cache-first.

returnPartialData

boolean

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

The default value is false.

refetchWritePolicy

"merge" | "overwrite"

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

The default value is "overwrite".

skip (deprecated)

boolean

If true, the 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

queryRef

QueryReference<TData>

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

Helper functions

refetch

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

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

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

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

fetchMore

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

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

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

useReadQuery
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

ParamTypeDescription
queryRefQueryReferenceThe queryRef that was generated via useBackgroundQuery.

Result

Name /
Type
Description

Operation result

data

TData

An object containing the result of your after it completes.

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

error

ApolloError

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

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

networkStatus

NetworkStatus

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

useLoadableQuery
Since 3.9.0

A hook for imperatively loading a , 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

import { gql, useLoadableQuery } from "@apollo/client";
const GET_GREETING = gql`
query GetGreeting($language: String!) {
greeting(language: $language) {
message
}
}
`;
function App() {
const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);
return (
<>
<button onClick={() => loadGreeting({ language: "english" })}>
Load greeting
</button>
<Suspense fallback={<div>Loading...</div>}>
{queryRef && <Hello queryRef={queryRef} />}
</Suspense>
</>
);
}
function Hello({ queryRef }) {
const { data } = useReadQuery(queryRef);
return <div>{data.greeting.message}</div>;
}

Signature

function useLoadableQuery<TData, TVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: LoadableQueryHookOptions
): UseLoadableQueryResult<TData, TVariables>

(src/react/hooks/useLoadableQuery.ts)

Parameters

Name / Type
Description

query

DocumentNode | TypedDocumentNode<TData, TVariables>

A parsed into an AST by gql.

options (optional)

LoadableQueryHookOptions

Options to control how the is executed.

Show/hide child attributes
Operation options
ApolloClient<any>

The instance of ApolloClient to use to execute the .

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

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

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

string | number | any[]

A unique identifier for the . Each item in the array must be a stable identifier to prevent infinite fetches.

This is useful when using the same and 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.

Networking options
DefaultContext

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

Caching options
LoadableQueryHookFetchPolicy

Specifies how the interacts with the 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.

Specifies whether a NetworkStatus.refetch should merge incoming data with existing data, or overwrite the existing data. Overwriting is probably preferable, but merging is currently the default behavior, for backwards compatibility with 3.x.

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

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

[
loadQuery: LoadQueryFunction<TVariables>,
queryRef: QueryReference<TData, TVariables> | null,
{
fetchMore: FetchMoreFunction<TData, TVariables>;
refetch: RefetchFunction<TData, TVariables>;
reset: ResetFunction;
}
]
A tuple of three values:
NameTypeDescription
loadQueryLoadQueryFunction<TVariables>A function used to imperatively load a query. Calling this function will create or update the `queryRef` returned by `useLoadableQuery`, which should be passed to `useReadQuery`.
queryRefQueryReference<TData, TVariables> | nullThe `queryRef` used by `useReadQuery` to read the query result.
Show/hide child attributes
Other
() => Promise<QueryReference<TData, TVariables>>

This is in alpha stage and is subject to breaking changes.

A function that returns a promise that resolves when the has finished loading. The promise resolves with the QueryReference itself.

This method is useful for preloading queries in data loading , such as React Router or TanStack Router, to prevent routes from transitioning until the has finished loading. data is not exposed on the promise to discourage using the data in loader functions and exposing it to your route components. Instead, we prefer you rely on useReadQuery to access the data to ensure your component can rerender with cache updates. If you need to access raw data, use client.query() directly.

handlers{ fetchMore: FetchMoreFunction<TData, TVariables>; refetch: RefetchFunction<TData, TVariables>; reset: ResetFunction; }Additional handlers used for the query, such as `refetch`.

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

const MyComponent({ queryRef }) {
const { refetch, fetchMore } = useQueryRefHandlers(queryRef);
// ...
}

Signature

function useQueryRefHandlers<TData, TVariables>(
queryRef: QueryReference<TData, TVariables>
): UseQueryRefHandlersResult<TData, TVariables>

(src/react/hooks/useQueryRefHandlers.ts)

Parameters

Name / Type
Description

queryRef

QueryReference<TData, TVariables>

A QueryReference returned from useBackgroundQuery, useLoadableQuery, or createQueryPreloader.

Show/hide child attributes
Other
() => Promise<QueryReference<TData, TVariables>>

This is in alpha stage and is subject to breaking changes.

A function that returns a promise that resolves when the has finished loading. The promise resolves with the QueryReference itself.

This method is useful for preloading queries in data loading , such as React Router or TanStack Router, to prevent routes from transitioning until the has finished loading. data is not exposed on the promise to discourage using the data in loader functions and exposing it to your route components. Instead, we prefer you rely on useReadQuery to access the data to ensure your component can rerender with cache updates. If you need to access raw data, use client.query() directly.

Result

UseQueryRefHandlersResult<TData, TVariables>
Show/hide child attributes
Other
FetchMoreFunction<TData, TVariables>

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

RefetchFunction<TData, TVariables>

Update the of this observable , and fetch the new results. This method should be preferred over setVariables in most use cases.

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.

Recommended usage of skipToken with useSuspenseQuery
import { skipToken, useSuspenseQuery } from '@apollo/client';
const { data } = useSuspenseQuery(
query,
id ? { variables: { id } } : skipToken
);
Recommended usage of skipToken with useBackgroundQuery
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 if a certain 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 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.

Previous
ObservableQuery
Next
Preloading
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company