Apollo Client 4.x Guide
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Version 4.x brings improved caching, better TypeScript support, and React 19 compatibility.
Framework-Specific Setup Guides
For modern React frameworks with SSR support, use these specialized setup guides:
These guides provide framework-specific integration packages and patterns optimized for SSR, streaming, and React Server Components.
Quick Start
Step 1: Install
bash
1npm install @apollo/client graphql rxjs
Step 1.5: Set up TypeScript Code Generation (optional but recommended)
For TypeScript type generation (recommended):
bash
1npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typed-document-node
typescript
1// codegen.ts
2import { CodegenConfig } from "@graphql-codegen/cli";
3
4const config: CodegenConfig = {
5 overwrite: true,
6 schema: "<URL_OF_YOUR_GRAPHQL_API>",
7 // This assumes that all your source files are in a top-level `src/` directory - you might need to adjust this to your file structure
8 documents: ["src/**/*.{ts,tsx}"],
9 // Don't exit with non-zero status when there are no documents
10 ignoreNoDocuments: true,
11 generates: {
12 // Use a path that works the best for the structure of your application
13 "./src/types/__generated__/graphql.ts": {
14 plugins: ["typescript", "typescript-operations", "typed-document-node"],
15 config: {
16 avoidOptionals: {
17 // Use `null` for nullable fields instead of optionals
18 field: true,
19 // Allow nullable input fields to remain unspecified
20 inputValue: false,
21 },
22 // Use `unknown` instead of `any` for unconfigured scalars
23 defaultScalarType: "unknown",
24 // Apollo Client always includes `__typename` fields
25 nonOptionalTypename: true,
26 // Apollo Client doesn't add the `__typename` field to root types so
27 // don't generate a type for the `__typename` for root operation types.
28 skipTypeNameForRoot: true,
29 },
30 },
31 },
32};
33
34export default config;
The typed-document-node plugin might have a bundle size tradeoff but can prevent inconsistencies and is best suited for usage with LLMs, so it is recommended for most applications.
See the GraphQL Code Generator documentation for other recommended configuration patterns if required.
Step 2: Create Client
typescript
1import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
2import { SetContextLink } from "@apollo/client/link/context";
3
4const httpLink = new HttpLink({
5 uri: "https://your-graphql-endpoint.com/graphql",
6});
7
8// Use SetContextLink for auth headers to update dynamically per request
9const authLink = new SetContextLink(({ headers }) => {
10 const token = localStorage.getItem("token");
11 return {
12 headers: {
13 ...headers,
14 authorization: token ? `Bearer ${token}` : "",
15 },
16 };
17});
18
19const client = new ApolloClient({
20 link: authLink.concat(httpLink),
21 cache: new InMemoryCache(),
22});
Step 3: Setup Provider
tsx
1import { ApolloProvider } from "@apollo/client";
2import App from "./App";
3
4function Root() {
5 return (
6 <ApolloProvider client={client}>
7 <App />
8 </ApolloProvider>
9 );
10}
Step 4: Execute Query
tsx
1import { gql } from "@apollo/client";
2import { useQuery } from "@apollo/client/react";
3
4const GET_USERS = gql`
5 query GetUsers {
6 users {
7 id
8 name
9 email
10 }
11 }
12`;
13
14function UserList() {
15 const { loading, error, data } = useQuery(GET_USERS);
16
17 if (loading) return <p>Loading...</p>;
18 if (error) return <p>Error: {error.message}</p>;
19
20 return (
21 <ul>
22 {data.users.map((user) => (
23 <li key={user.id}>{user.name}</li>
24 ))}
25 </ul>
26 );
27}
Basic Query Usage
Using Variables
tsx
1const GET_USER = gql`
2 query GetUser($id: ID!) {
3 user(id: $id) {
4 id
5 name
6 email
7 }
8 }
9`;
10
11function UserProfile({ userId }: { userId: string }) {
12 const { loading, error, data, dataState } = useQuery(GET_USER, {
13 variables: { id: userId },
14 });
15
16 if (loading) return <p>Loading...</p>;
17 if (error) return <p>Error: {error.message}</p>;
18
19 return <div>{data.user.name}</div>;
20}
Note for TypeScript users: Use dataState for more robust type safety and better type narrowing in Apollo Client 4.x.
TypeScript Integration
typescript
1// Define types for codegen or TypedDocumentNode
2interface GetUserData {
3 user: {
4 id: string;
5 name: string;
6 email: string;
7 };
8}
9
10interface GetUserVariables {
11 id: string;
12}
13
14// Types are inferred from TypedDocumentNode - never use manual generics
15const GET_USER: TypedDocumentNode<GetUserData, GetUserVariables> = gql`
16 query GetUser($id: ID!) {
17 user(id: $id) {
18 id
19 name
20 email
21 }
22 }
23`;
24
25const { data } = useQuery(GET_USER, {
26 variables: { id: userId },
27});
28
29// data.user is automatically typed from GET_USER
Basic Mutation Usage
tsx
1import { gql, TypedDocumentNode } from "@apollo/client";
2import { useMutation } from "@apollo/client/react";
3
4interface CreateUserMutation {
5 createUser: {
6 id: string;
7 name: string;
8 email: string;
9 };
10}
11
12interface CreateUserMutationVariables {
13 input: {
14 name: string;
15 email: string;
16 };
17}
18
19const CREATE_USER: TypedDocumentNode<
20 CreateUserMutation,
21 CreateUserMutationVariables
22> = gql`
23 mutation CreateUser($input: CreateUserInput!) {
24 createUser(input: $input) {
25 id
26 name
27 email
28 }
29 }
30`;
31
32function CreateUserForm() {
33 const [createUser, { loading, error }] = useMutation(CREATE_USER);
34
35 const handleSubmit = async (formData: FormData) => {
36 const { data } = await createUser({
37 variables: {
38 input: {
39 name: formData.get("name") as string,
40 email: formData.get("email") as string,
41 },
42 },
43 });
44 if (data) {
45 console.log("Created user:", data.createUser);
46 }
47 };
48
49 return (
50 <form
51 onSubmit={(e) => {
52 e.preventDefault();
53 handleSubmit(new FormData(e.currentTarget));
54 }}
55 >
56 <input name="name" placeholder="Name" />
57 <input name="email" placeholder="Email" />
58 <button type="submit" disabled={loading}>
59 {loading ? "Creating..." : "Create User"}
60 </button>
61 {error && <p>Error: {error.message}</p>}
62 </form>
63 );
64}
Client Configuration Options
typescript
1const client = new ApolloClient({
2 // Required: The cache implementation
3 cache: new InMemoryCache({
4 typePolicies: {
5 Query: {
6 fields: {
7 // Field-level cache configuration
8 },
9 },
10 },
11 }),
12
13 // Network layer
14 link: new HttpLink({ uri: "/graphql" }),
15
16 // Avoid defaultOptions if possible as they break TypeScript expectations.
17 // Configure options per-query/mutation instead for better type safety.
18 // defaultOptions: {
19 // watchQuery: { fetchPolicy: 'cache-and-network' },
20 // },
21
22 // DevTools are enabled by default in development
23 // Only configure when enabling in production
24 devtools: {
25 enabled: true, // Only needed for production
26 },
27
28 // Custom name for this client instance
29 clientAwareness: {
30 name: "web-client",
31 version: "1.0.0",
32 },
33});
Reference Files
Detailed documentation for specific topics:
- Queries - useQuery, useLazyQuery, polling, refetching
- Mutations - useMutation, optimistic UI, cache updates
- Caching - InMemoryCache, typePolicies, cache manipulation
- State Management - Reactive variables, local state
- Error Handling - Error policies, error links, retries
- Troubleshooting - Common issues and solutions
Key Rules
Query Best Practices
- Each page should generally only have one query, composed from colocated fragments. Use
useFragment or useSuspenseFragment in all non-page-components. Use @defer to allow slow fields below the fold to stream in later and avoid blocking the page load.
- Fragments are for colocation, not reuse. Each fragment should describe exactly the data needs of a specific component, not be shared across components for common fields. See Fragment Colocation.
- Always handle
loading and error states in UI when using non-suspenseful hooks (useQuery, useLazyQuery). When using Suspense hooks (useSuspenseQuery, useBackgroundQuery), React handles this through <Suspense> boundaries and error boundaries.
- Use
fetchPolicy to control cache behavior per query
- Use the TypeScript type server to look up documentation for functions and options (Apollo Client has extensive docblocks)
Mutation Best Practices
- If the schema permits, mutation return values should return everything necessary to update the cache. Neither manual updates nor refetching should be necessary.
- If the mutation response is insufficient, carefully weigh manual cache manipulation vs refetching. Manual updates risk missing server logic. Consider optimistic updates with a granular refetch if needed.
- Handle errors gracefully in the UI
- Use
refetchQueries sparingly (prefer letting the cache update automatically)
Caching Best Practices
- Configure
keyFields for types without id field
- Disable normalization by setting
keyFields: false for types that don't include an identifier and are meant to group related fields under the parent
- Use
typePolicies for pagination and computed fields
- Understand cache normalization to debug issues
- Enable data masking for all new applications - it prevents components from accessing fragment data they don't own, enforcing proper data boundaries and preventing over-rendering
- Avoid over-fetching with proper field selection
- Configure appropriate
fetchPolicy per use case
- Use
@defer for incremental delivery of deferred query parts, and @stream for streaming list fields (@stream available in Apollo Client 4.1+)
- Prefer Suspense hooks (
useSuspenseQuery, useBackgroundQuery) in modern applications for better loading state handling and code simplicity
Ground Rules
- ALWAYS use Apollo Client 4.x patterns (not v3 or earlier)
- ALWAYS wrap your app with
ApolloProvider
- ALWAYS handle loading and error states when using non-suspenseful hooks
- PREFER Suspense hooks (
useSuspenseQuery, useBackgroundQuery) in modern applications for better DX
- NEVER store Apollo Client in React state (use module-level or context)
- PREFER
cache-first for read-heavy data, network-only for real-time data
- USE TypeScript for better type safety with GraphQL
- IMPLEMENT proper cache updates instead of refetching entire queries
- ADVISE the human steering you to look into Apollo DevTools when collaboratively debugging Apollo Client issues