/
Launch Apollo Studio

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

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 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 React from 'react';
import { ApolloConsumer } from '@apollo/client';

const WithApolloClient = () => (
  <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.

Function Signature

function useQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>,
): QueryResult<TData, TVariables> {}

Params

query

ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by gql.

options

Name /
Type
Description

Operation options

query

DocumentNode

A GraphQL query string parsed into an AST with the gql template literal.

Optional for the useQuery hook, because the query can be provided as the first parameter to the hook. Required for the Query component.

variables

{ [key: string]: any }

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

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

errorPolicy

ErrorPolicy

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

For details, see GraphQL error policies.

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

onCompleted

(data: TData | {}) => void

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.

onError

(error: ApolloError) => void

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.

skip

boolean

If true, the query is not executed. Not available with useLazyQuery.

This property is part of Apollo Client's React integration, and it is not available in the core ApolloClient API.

The default value is false.

displayName

string

The name of your component to be displayed in the React Developer Tools.

The default value is Query.

Networking options

pollInterval

number

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

The default value is 0 (no polling).

notifyOnNetworkStatusChange

boolean

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.

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.

ssr

boolean

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

client

ApolloClient

The instance of ApolloClient to use to execute the query.

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

Caching options

fetchPolicy

FetchPolicy

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 cache-first.

nextFetchPolicy

FetchPolicy

Specifies the fetchPolicy to use for all executions of this query after this execution.

For example, you can use this to switch back to a cache-first fetch policy after using cache-and-network or network-only for a single execution.

returnPartialData

boolean

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

The default value is false.

Deprecated options

partialRefetch

boolean

Deprecated. If true, causes a query refetch if the query result is detected as partial. Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

The default value is false.

Result

Name /
Type
Description

Operation data

data

TData

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

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

previousData

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.

error

ApolloError

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

For more information, see Handling operation errors.

variables

{ [key: string]: any }

An object containing the variables that were provided for the query.

Network info

loading

boolean

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

networkStatus

NetworkStatus

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

Used in conjunction with the notifyOnNetworkStatusChange option.

client

ApolloClient

The instance of Apollo Client that executed the query.

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

called

boolean

If true, the associated lazy query has been executed.

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

Helper functions

refetch

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

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

The fetchPolicy for the refetched query will be set to network-only, unless the fetchPolicy is already no-cache or cache-and-network (which also guarantee a network request).

See also Refetching.

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.

startPolling

(interval: number) => void

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

stopPolling

() => void

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

subscribeToMore

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

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

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

updateQuery

(previousResult: TData, options: { variables: TVariables }) => TData

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

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.

Function Signature

function useLazyQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: LazyQueryHookOptions<TData, TVariables>,
): [
  (options?: QueryLazyOptions<TVariables>) => void,
  QueryResult<TData, TVariables>
] {}

Params

query

ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by gql.

options

Name /
Type
Description

Operation options

query

DocumentNode

A GraphQL query string parsed into an AST with the gql template literal.

Optional for the useQuery hook, because the query can be provided as the first parameter to the hook. Required for the Query component.

variables

{ [key: string]: any }

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

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

errorPolicy

ErrorPolicy

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

For details, see GraphQL error policies.

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

onCompleted

(data: TData | {}) => void

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.

onError

(error: ApolloError) => void

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.

skip

boolean

If true, the query is not executed. Not available with useLazyQuery.

This property is part of Apollo Client's React integration, and it is not available in the core ApolloClient API.

The default value is false.

displayName

string

The name of your component to be displayed in the React Developer Tools.

The default value is Query.

Networking options

pollInterval

number

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

The default value is 0 (no polling).

notifyOnNetworkStatusChange

boolean

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.

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.

ssr

boolean

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

client

ApolloClient

The instance of ApolloClient to use to execute the query.

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

Caching options

fetchPolicy

FetchPolicy

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 cache-first.

nextFetchPolicy

FetchPolicy

Specifies the fetchPolicy to use for all executions of this query after this execution.

For example, you can use this to switch back to a cache-first fetch policy after using cache-and-network or network-only for a single execution.

returnPartialData

boolean

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

The default value is false.

Deprecated options

partialRefetch

boolean

Deprecated. If true, causes a query refetch if the query result is detected as partial. Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

The default value is false.

Result

Execute function

ParamTypeDescription
Execute function(options?: QueryLazyOptions<TVariables>) => voidFunction that can be triggered to execute the suspended query. After being called, useLazyQuery behaves just like useQuery.

Result object

Name /
Type
Description

Operation data

data

TData

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

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

previousData

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.

error

ApolloError

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

For more information, see Handling operation errors.

variables

{ [key: string]: any }

An object containing the variables that were provided for the query.

Network info

loading

boolean

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

networkStatus

NetworkStatus

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

Used in conjunction with the notifyOnNetworkStatusChange option.

client

ApolloClient

The instance of Apollo Client that executed the query.

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

called

boolean

If true, the associated lazy query has been executed.

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

Helper functions

refetch

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

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

The fetchPolicy for the refetched query will be set to network-only, unless the fetchPolicy is already no-cache or cache-and-network (which also guarantee a network request).

See also Refetching.

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.

startPolling

(interval: number) => void

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

stopPolling

() => void

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

subscribeToMore

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

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

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

updateQuery

(previousResult: TData, options: { variables: TVariables }) => TData

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

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

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

Function Signature

function useMutation<TData = any, TVariables = OperationVariables>(
  mutation: DocumentNode,
  options?: MutationHookOptions<TData, TVariables>,
): MutationTuple<TData, TVariables> {}

Params

mutation

ParamTypeDescription
mutationDocumentNodeA GraphQL mutation document parsed into an AST by gql.

options

Name /
Type
Description

Operation options

mutation

DocumentNode

A GraphQL query string parsed into an AST with the gql template literal.

Optional for the useMutation hook, because the mutation can also be provided as the first parameter to the hook.

Required for the Mutation component.

variables

{ [key: string]: any }

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.

errorPolicy

ErrorPolicy

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 none, meaning that the mutation result includes error details but not partial results.

onCompleted

(data: TData | {}) => void

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

onError

(error: ApolloError) => void

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

onQueryUpdated

(observableQuery: ObservableQuery, diff: Cache.DiffResult, lastDiff: Cache.DiffResult | undefined) => boolean | TResult

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.

refetchQueries

Array<string | { query: DocumentNode, variables?: TVariables}> | ((mutationResult: FetchResult) => Array<string | { query: DocumentNode, variables?: TVariables}>)

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:

  • An object containing the query to execute, along with any variables
  • A string indicating the operation name of the query to refetch
awaitRefetchQueries

boolean

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

ignoreResults

boolean

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

The default value is false.

Networking options

notifyOnNetworkStatusChange

boolean

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.

client

ApolloClient

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.

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.

Caching options

update

(cache: ApolloCache, mutationResult: FetchResult) => void

A function used to update the Apollo Client cache after the mutation completes.

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

optimisticResponse

Object

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.

Result

Mutate function:

Name /
Type
Description
mutate

(options?: MutationOptions) => Promise<FetchResult>

A function to trigger the mutation from your UI. You can optionally pass this function any of the following options:

  • awaitRefetchQueries
  • context
  • fetchPolicy
  • optimisticResponse
  • refetchQueries
  • update
  • variables

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 mutation result.

Mutation result:

Name /
Type
Description
data

TData

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

loading

boolean

If true, the mutation is currently in flight.

error

ApolloError

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

called

boolean

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

client

ApolloClient

The instance of Apollo Client that executed the mutation.

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

useSubscription

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

Refer to the Subscriptions section for a more in-depth overview of useSubscription.

Function Signature

function useSubscription<TData = any, TVariables = OperationVariables>(
  subscription: DocumentNode,
  options?: SubscriptionHookOptions<TData, TVariables>,
): {
  variables: TVariables;
  loading: boolean;
  data?: TData;
  error?: ApolloError;
} {}

Params

subscription

ParamTypeDescription
subscriptionDocumentNodeA GraphQL subscription document parsed into an AST by gql.

options

OptionTypeDescription
subscriptionDocumentNodeA 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
shouldResubscribebooleanDetermines if your subscription should be unsubscribed and subscribed again
onSubscriptionData(options: OnSubscriptionDataOptions<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 subscriptionData.
fetchPolicyFetchPolicyHow you want your component to interact with the Apollo cache. For details, see Setting a fetch policy.
contextRecord<string, any>Shared context between your component and your network interface (Apollo Link).
clientApolloClientAn ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in.

Result

PropertyTypeDescription
dataTDataAn object containing the result of your GraphQL subscription. Defaults to an empty object.
loadingbooleanA boolean that indicates whether any initial data has been returned
errorApolloErrorA 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`)
}

Function Signature

function useApolloClient(): ApolloClient<object> {}

Result

ParamTypeDescription
Apollo Client instanceApolloClient<object>The ApolloClient instance being used by the application.
Edit on GitHub