apollo-client
작성자: apollographql
Apollo Client는 로컬 및 원격 데이터를 GraphQL로 관리할 수 있게 해주는 JavaScript용 종합 상태 관리 라이브러리입니다. 버전 4.x는 개선된 캐싱, 더 나은 TypeScript 지원, React 19 호환성을 제공합니다.
npx skills add https://github.com/apollographql/apollo-client --skill apollo-clientApollo 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 - For client-side React applications without SSR (Vite, Create React App, etc.)
- Next.js App Router - For Next.js applications using the App Router with React Server Components
- React Router Framework Mode - For React Router 7 applications with streaming SSR
- TanStack Start - 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
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:
- TypeScript Code Generation - GraphQL Code Generator setup for type-safe operations
- Queries - useQuery, useLazyQuery, polling, refetching
- Suspense Hooks - useSuspenseQuery, useBackgroundQuery, useReadQuery, useLoadableQuery
- Mutations - useMutation, optimistic UI, cache updates
- Fragments - Fragment colocation, useFragment, useSuspenseFragment, data masking
- 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
useFragmentoruseSuspenseFragmentin all non-page-components. Use@deferto 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
loadinganderrorstates 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
fetchPolicyto 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
refetchQueriessparingly (prefer letting the cache update automatically)
Caching Best Practices
- Configure
keyFieldsfor types withoutidfield - Disable normalization by setting
keyFields: falsefor types that don't include an identifier and are meant to group related fields under the parent - Use
typePoliciesfor 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
fetchPolicyper use case - Use
@deferfor incremental delivery of deferred query parts, and@streamfor streaming list fields (@streamavailable 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-firstfor read-heavy data,network-onlyfor 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 4.x를 사용하여 React 애플리케이션을 구축하기 위한 종합 가이드로, 쿼리, 뮤테이션, 캐싱 및 상태 관리를 다룹니다. 여러 React 프레임워크 및 설정을 지원합니다: 클라이언트 측 앱(Vite, CRA), React Server Components를 사용하는 Next.js App Router, 스트리밍 SSR을 지원하는 React Router 7, TanStack Start. 쿼리(useQuery, useLazyQuery), 뮤테이션(useMutation)을 위한 훅과 최신 React 18+ 및 19를 위한 Suspense 기반 패턴(useSuspenseQuery, useBackgroundQuery)을 포함합니다.
official
apollo-connectors
apollographql
REST API를 @source 및 @connect 지시문을 사용하여 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 연산과 스키마에서 Kotlin 모델을 생성하는 강력한 타입의 GraphQL 클라이언트로, Android, JVM 및 Kotlin Multiplatform 프로젝트에서 사용할 수 있습니다.
official
apollo-mcp-server
apollographql
AI 에이전트를 GraphQL API에 연결하여 Model Context Protocol을 통해 내장된 인트로스펙션 및 작업 도구를 제공합니다. GraphQL 작업을 MCP 도구로 노출하며, 로컬 파일, GraphOS Studio 컬렉션, 지속적 쿼리 매니페스트의 세 가지 작업 소스를 지원합니다. 스키마 탐색 및 임시 쿼리 테스트를 위한 네 가지 인트로스펙션 도구(introspect, search, validate, execute)를 제공하며, 축약 표기법을 사용한 미니피케이션 모드로 토큰 사용량을 줄입니다. 정적 헤더를 통한 구성 가능한 인증,...
official
apollo-router
apollographql
Apollo Router는 Apollo Federation 2 슈퍼그래프를 실행하기 위해 Rust로 작성된 고성능 그래프 라우터입니다. 서브그래프 앞에 위치하여 쿼리 계획, 실행 및 응답 구성을 처리합니다.
official
apollo-router-plugin-creator
apollographql
Apollo Router용 네이티브 Rust 플러그인을 생성합니다.
official