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 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
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 |
| The name of your component to be displayed in the React Developer Tools. 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
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL query. Defaults to undefined . |
previousData | TData | An object containing the previous result of your GraphQL query (the last result before a new data value was set). Defaults to undefined . |
loading | boolean | A boolean that indicates whether the request is in flight |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
variables | { [key: string]: any } | An object containing the variables the query was called with |
networkStatus | NetworkStatus | A number from 1-8 (1 = loading , 2 = setVariables , 3 = fetchMore , 4 = refetch , 6 = poll , 7 = ready , 8 = error ) corresponding to the detailed state of your network request. Includes information about refetching and polling status. Used in conjunction with the notifyOnNetworkStatusChange prop. |
refetch | (variables?: Partial<TVariables>) => Promise<ApolloQueryResult> | A function that allows you to refetch the query and optionally pass in new variables |
fetchMore | ({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult> | A function that enables pagination for your query |
startPolling | (interval: number) => void | This function sets up an interval in ms and fetches the query each time the specified interval passes. |
stopPolling | () => void | This function stops the query from polling. |
subscribeToMore | (options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => void | A function that sets up a subscription. subscribeToMore returns a function that you can use to unsubscribe. |
updateQuery | (previousResult: TData, options: { variables: TVariables }) => TData | A function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription |
client | ApolloClient | Your ApolloClient instance. Useful for manually firing queries or writing data to the cache. |
called | boolean | A boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query ). |
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
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 |
| The name of your component to be displayed in the React Developer Tools. 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
Execute function
Param | Type | Description |
---|---|---|
Execute function | (options?: QueryLazyOptions<TVariables>) => void | Function that can be triggered to execute the suspended query. After being called, useLazyQuery behaves just like useQuery . |
Result object
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL query. Defaults to undefined . |
previousData | TData | An object containing the previous result of your GraphQL query (the last result before a new data value was set). Defaults to undefined . |
loading | boolean | A boolean that indicates whether the request is in flight |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
variables | { [key: string]: any } | An object containing the variables the query was called with |
networkStatus | NetworkStatus | A number from 1-8 (1 = loading , 2 = setVariables , 3 = fetchMore , 4 = refetch , 6 = poll , 7 = ready , 8 = error ) corresponding to the detailed state of your network request. Includes information about refetching and polling status. Used in conjunction with the notifyOnNetworkStatusChange prop. |
refetch | (variables?: Partial<TVariables>) => Promise<ApolloQueryResult> | A function that allows you to refetch the query and optionally pass in new variables |
fetchMore | ({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult> | A function that enables pagination for your query |
startPolling | (interval: number) => void | This function sets up an interval in ms and fetches the query each time the specified interval passes. |
stopPolling | () => void | This function stops the query from polling. |
subscribeToMore | (options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => void | A function that sets up a subscription. subscribeToMore returns a function that you can use to unsubscribe. |
updateQuery | (previousResult: TData, options: { variables: TVariables }) => TData | A function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription |
client | ApolloClient | Your ApolloClient instance. Useful for manually firing queries or writing data to the cache. |
called | boolean | A boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query ). |
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
Param | Type | Description |
---|---|---|
mutation | DocumentNode | A GraphQL mutation document parsed into an AST by gql . |
options
Option | Type | Description |
---|---|---|
mutation | DocumentNode | A GraphQL mutation document parsed into an AST by graphql-tag . Optional for the useMutation Hook since the mutation can be passed in as the first parameter to the Hook. Required for the Mutation component. |
variables | { [key: string]: any } | An object containing all of the variables your mutation needs to execute |
update | (cache: DataProxy, mutationResult: FetchResult) | A function used to update the cache after a mutation occurs |
ignoreResults | boolean | If true, the returned data property will not update with the mutation result. |
optimisticResponse | Object | Provide a mutation response before the result comes back from the server |
refetchQueries | Array<string|{ query: DocumentNode, variables?: TVariables}> | ((mutationResult: FetchResult) => Array<string|{ query: DocumentNode, variables?: TVariables}>) | An array or function that allows you to specify which queries you want to refetch after a mutation has occurred. Array values can either be queries (with optional variables) or just the string names of queries to be refeteched. |
awaitRefetchQueries | boolean | Queries refetched as part of refetchQueries are handled asynchronously, and are not waited on before the mutation is completed (resolved). Setting this to true will make sure refetched queries are completed before the mutation is considered done. false by default. |
onCompleted | (data: TData) => void | A callback executed once your mutation successfully completes |
onError | (error: ApolloError) => void | A callback executed in the event of an error. |
context | Record<string, any> | Shared context between your component and your network interface (Apollo Link). Useful for setting headers from props or sending information to the request function of Apollo Boost. |
client | ApolloClient | An ApolloClient instance. By default useMutation / Mutation uses the client passed down via context, but a different client can be passed in. |
Result
Mutate function:
Property | Type | Description |
---|---|---|
mutate | (options?: MutationOptions) => Promise<FetchResult> | A function to trigger a mutation from your UI. You can optionally pass variables , optimisticResponse , refetchQueries , and update in as options, which will override options/props passed to useMutation / Mutation . The function returns a promise that fulfills with your mutation result. |
Mutation result:
Property | Type | Description |
---|---|---|
data | TData | The data returned from your mutation. It can be undefined if ignoreResults is true. |
loading | boolean | A boolean indicating whether your mutation is in flight |
error | ApolloError | Any errors returned from the mutation |
called | boolean | A boolean indicating if the mutate function has been called |
client | ApolloClient | Your ApolloClient instance. Useful for invoking cache methods outside the context of the update function, such as client.writeData and client.readQuery . |
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
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 |
skip | boolean | If skip is true , the subscription will be skipped entirely |
onSubscriptionData | (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 . |
fetchPolicy | FetchPolicy | How you want your component to interact with the Apollo cache. Defaults to "cache-first". |
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`)
}
Function Signature
function useApolloClient(): ApolloClient<object> {}
Result
Param | Type | Description |
---|---|---|
Apollo Client instance | ApolloClient<object> | The ApolloClient instance being used by the application. |