apollo-client

作者: apollographql

全面指南,涵蓋使用 Apollo Client 4.x 建構 React 應用程式,包含查詢、變更、快取及狀態管理。支援多種 React 框架與設定:客戶端應用程式(Vite、CRA)、搭配 React Server Components 的 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超級圖譜。提供結構化五步驟流程:研究API結構、使用指令實作綱要、透過rover supergraph compose驗證、執行連接器、測試覆蓋範圍。支援請求配置,包含標頭、請求主體、N+1模式批次處理,以及透過$env注入環境變數。處理回應映射,包含欄位選取、別名、巢狀資料子選取及實體...
official
apollo-federation
apollographql
Apollo Federation 可將多個 GraphQL API(子圖)組合成統一的超級圖表。
official
apollo-ios
apollographql
Apollo iOS 是一個專為 Apple 平台設計的強型別 GraphQL 客戶端。它能從你的 GraphQL 操作與 schema 生成 Swift 型別,並提供 async/await 客戶端、正規化快取(記憶體或 SQLite 支援)、可插拔的攔截器式 HTTP 傳輸(處理查詢、變更與多部分訂閱),以及可選的 WebSocket 傳輸(graphql-transport-ws),可承載任何操作類型。
official
apollo-kotlin
apollographql
Apollo Kotlin 是一個強型別的 GraphQL 客戶端,能從你的 GraphQL 操作和綱要中生成 Kotlin 模型,可用於 Android、JVM 和 Kotlin Multiplatform 專案。
official
apollo-mcp-server
apollographql
透過模型上下文協定將AI代理連接至GraphQL API,內建內省與操作工具。將GraphQL操作暴露為MCP工具;支援三種操作來源:本地檔案、GraphOS Studio集合與持久化查詢清單。提供四種內省工具(introspect、search、validate、execute)用於結構探索與臨時查詢測試;壓縮模式透過簡潔標記減少Token用量。可透過靜態標頭設定認證...
official
apollo-router
apollographql
Apollo Router 是一款以 Rust 編寫的高效能圖形路由器,用於執行 Apollo Federation 2 超級圖。它位於子圖前端,負責查詢規劃、執行與回應組合。
official
apollo-router-plugin-creator
apollographql
為 Apollo Router 建立原生 Rust 外掛程式。
official