---
name: apollo-client
description: >-
  Guide for building React applications with Apollo Client 4.x. Use this skill when: (1) setting up Apollo Client in a React project, (2) writing GraphQL queries or mutations with hooks, (3) configuring caching or cache policies, (4) managing local state with reactive variables, (5) troubleshooting Apollo Client errors or performance issues.
license: MIT
compatibility: React 18+, React 19 (Suspense/RSC). Works with Next.js, Vite, CRA, and other React frameworks.
metadata:
  author: apollographql
  version: "1.0.0"
allowed-tools: Bash(npm:*) Bash(npx:*) Bash(node:*) Read Write Edit Glob Grep
title: apollo-client
canonical_url: https://skilld.dev/gh/apollographql/apollo-client
last_updated: 2026-10-30T07:01:26.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/caching.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/caching.md), [references/error-handling.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/error-handling.md), [references/fragments.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/fragments.md), [references/integration-client.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-client.md), [references/integration-nextjs.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-nextjs.md), [references/integration-react-router.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-react-router.md), [references/integration-tanstack-start.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-tanstack-start.md), [references/mutations.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/mutations.md), [references/queries.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/queries.md), [references/state-management.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/state-management.md), [references/suspense-hooks.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/suspense-hooks.md), [references/troubleshooting.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/troubleshooting.md), [references/typescript-codegen.md](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/typescript-codegen.md).
>
> If the user asked to install this Skill, run `npx skilld install apollographql/apollo-client/apollo-client`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/apollo-client`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/apollographql/apollo-client/apollo-client) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/apollo-client`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/apollo-client --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/apollo-client --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

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

## Integration Guides

Choose the integration guide that matches your application setup:

- **[Client-Side Apps](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-client.md)** - For client-side React applications without SSR (Vite, Create React App, etc.)
- **[Next.js App Router](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-nextjs.md)** - For Next.js applications using the App Router with React Server Components
- **[React Router Framework Mode](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-react-router.md)** - For React Router 7 applications with streaming SSR
- **[TanStack Start](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/integration-tanstack-start.md)** - For TanStack Start applications with modern routing

Each guide includes installation steps, configuration, and framework-specific patterns optimized for that environment.

## Quick Reference

### Basic Query

```tsx
import { gql } from "@apollo/client";
import { useQuery } from "@apollo/client/react";

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
    }
  }
`;

function UserProfile({ userId }: { userId: string }) {
  const { loading, error, data, dataState } = useQuery(GET_USER, {
    variables: { id: userId },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  // TypeScript note: for stricter type narrowing, you can also check `dataState === "complete"` before accessing data
  return <div>{data?.user.name}</div>;
}
```

### Basic Mutation

```tsx
import { gql } from "@apollo/client";
import { useMutation } from "@apollo/client/react";

const CREATE_USER = gql`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      id
      name
    }
  }
`;

function CreateUserForm() {
  const [createUser, { loading, error }] = useMutation(CREATE_USER);

  const handleSubmit = async (name: string) => {
    await createUser({ variables: { input: { name } } });
  };

  return <button onClick={() => handleSubmit("John")}>Create User</button>;
}
```

### Suspense Query

```tsx
import { Suspense } from "react";
import { useSuspenseQuery } from "@apollo/client/react";

function UserProfile({ userId }: { userId: string }) {
  const { data } = useSuspenseQuery(GET_USER, {
    variables: { id: userId },
  });

  return <div>{data.user.name}</div>;
}

function App() {
  return (
    <Suspense fallback={<p>Loading user...</p>}>
      <UserProfile userId="1" />
    </Suspense>
  );
}
```

## Reference Files

Detailed documentation for specific topics:

- [TypeScript Code Generation](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/typescript-codegen.md) - GraphQL Code Generator setup for type-safe operations
- [Queries](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/queries.md) - useQuery, useLazyQuery, polling, refetching
- [Suspense Hooks](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/suspense-hooks.md) - useSuspenseQuery, useBackgroundQuery, useReadQuery, useLoadableQuery
- [Mutations](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/mutations.md) - useMutation, optimistic UI, cache updates
- [Fragments](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/fragments.md) - Fragment colocation, useFragment, useSuspenseFragment, data masking
- [Caching](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/caching.md) - InMemoryCache, typePolicies, cache manipulation
- [State Management](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/state-management.md) - Reactive variables, local state
- [Error Handling](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/error-handling.md) - Error policies, error links, retries
- [Troubleshooting](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/troubleshooting.md) - 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 [Fragments reference](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/fragments.md) for details on fragment colocation and data masking.
- 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](https://skilld.dev/api/skills-raw/apollographql/apollo-client/apollo-client/references/fragments.md#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

### Performance

- 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
