apollo-client

作者: apollographql

全面指南,涵盖使用Apollo Client 4.x构建React应用的查询、变更、缓存和状态管理。支持多种React框架和配置:客户端应用(Vite、CRA)、带React服务端组件的Next.js App Router、带流式SSR的React Router 7,以及TanStack Start。包含查询(useQuery、useLazyQuery)、变更(useMutation)的钩子,以及基于Suspense的模式(useSuspenseQuery、useBackgroundQuery),适用于现代React 18+和19...

npx skills add https://github.com/apollographql/skills --skill apollo-client

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:

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

Quick Reference

Basic Query

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

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

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:

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

来自 apollographql 的更多技能

apollo-client
apollographql
Apollo Client 是一个全面的 JavaScript 状态管理库,使您能够通过 GraphQL 管理本地和远程数据。4.x 版本带来了改进的缓存、更好的 TypeScript 支持以及 React 19 兼容性。
official
apollo-connectors
apollographql
使用@source和@connect指令将REST API集成到GraphQL超级图中。提供结构化的5步流程:研究API结构、使用指令实现模式、通过rover supergraph compose验证、执行连接器以及测试覆盖。支持请求配置,包括标头、请求体负载、N+1模式的批处理以及通过$env注入环境变量。处理响应映射,包括字段选择、别名、嵌套数据的子选择以及实体...
official
apollo-federation
apollographql
Apollo Federation 支持将多个 GraphQL API(子图)组合成一个统一的超级图。
official
apollo-ios
apollographql
Apollo iOS 是一个面向 Apple 平台的强类型 GraphQL 客户端。它从你的 GraphQL 操作和模式生成 Swift 类型,并附带一个 async/await 客户端、一个规范化缓存(内存或 SQLite 支持)、一个可插拔的基于拦截器的 HTTP 传输层(处理查询、变更和多部分订阅),以及一个可选的 WebSocket 传输层(graphql-transport-ws),可承载任何操作类型。
official
apollo-kotlin
apollographql
Apollo Kotlin 是一个强类型的 GraphQL 客户端,能够根据你的 GraphQL 操作和模式生成 Kotlin 模型,可用于 Android、JVM 和 Kotlin 多平台项目。
official
apollo-mcp-server
apollographql
通过模型上下文协议将AI智能体连接到GraphQL API,内置内省与操作工具。将GraphQL操作暴露为MCP工具;支持三种操作来源:本地文件、GraphOS Studio集合和持久化查询清单。提供四种内省工具(introspect、search、validate、execute)用于模式探索和临时查询测试;压缩模式通过紧凑符号减少令牌使用。可通过静态标头配置身份验证...
official
apollo-router
apollographql
Apollo Router 是一个用 Rust 编写的高性能图形路由器,用于运行 Apollo Federation 2 超级图。它位于子图前端,负责查询规划、执行和响应组合。
official
apollo-router-plugin-creator
apollographql
为Apollo Router创建原生Rust插件。
official