Community코딩 & 개발github.com

apollographql/apollo-client

Apollo Client 4.x를 사용하여 React 애플리케이션을 구축하기 위한 가이드입니다. 이 기술은 다음 경우에 사용합니다: (1) React 프로젝트에서 Apollo Client 설정, (2) 훅을 사용한 GraphQL 쿼리 또는 뮤테이션 작성, (3) 캐싱 또는 캐시 정책 구성, (4) 반응형 변수를 사용한 로컬 상태 관리, (5) Apollo Client 오류 또는 성능 문제 해결.

apollo-client란 무엇인가요?

이 기술은 React 애플리케이션에서 Apollo Client 4.x를 효과적으로 사용하기 위한 종합 가이드입니다. Apollo Client는 GraphQL 데이터를 관리하기 위한 강력한 라이브러리로, 이 기술은 개발자가 프로젝트 초기 설정부터 고급 기능까지 단계별로 학습할 수 있도록 돕습니다. 주요 기능으로는 ApolloProvider를 통한 클라이언트 설정, `useQuery` 및 `useMutation` 훅을 사용한 데이터 fetching 및 변이, InMemoryCache 및 캐시 정책 구성, 반응형 변수를 사용한 로컬 상태 관리, 그리고 오류 처리 및 성능 최적화가 포함됩니다. 이 기술은 Cursor, Claude Code, Codex와 같은 AI 에이전트 플랫폼에서 사용할 수 있으며, 개발자가 GraphQL 기반 React 앱을 더 빠르고 안정적으로 구축할 수 있도록 실용적인 조언과 모범 사례를 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
Part ofReact
npx skills add https://github.com/apollographql/skills/tree/main/skills/apollo-client

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

apollo-client은(는) 무엇을 하나요?

Apollo Client 4.x를 사용하여 React 애플리케이션을 구축하기 위한 가이드입니다. 이 기술은 다음 경우에 사용합니다: (1) React 프로젝트에서 Apollo Client 설정, (2) 훅을 사용한 GraphQL 쿼리 또는 뮤테이션 작성, (3) 캐싱 또는 캐시 정책 구성, (4) 반응형 변수를 사용한 로컬 상태 관리, (5) Apollo Client 오류 또는 성능 문제 해결.

설치

npm install @apollo/client graphql

기본 설정

ApolloProvider를 사용하여 React 컴포넌트 트리에 Apollo Client를 연결합니다.

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://your-graphql-endpoint.com/graphql',
  cache: new InMemoryCache()
});

function App() {
  return (
    <ApolloProvider client={client}>
      <div>
        <h1>내 Apollo 앱</h1>
      </div>
    </ApolloProvider>
  );
}

쿼리 실행

useQuery 훅을 사용하여 데이터를 가져옵니다.

import { gql, useQuery } from '@apollo/client';

const GET_ITEMS = gql`
  query GetItems {
    items {
      id
      name
    }
  }
`;

function ItemsList() {
  const { loading, error, data } = useQuery(GET_ITEMS);

  if (loading) return <p>로딩 중...</p>;
  if (error) return <p>오류: {error.message}</p>;

  return (
    <ul>
      {data.items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

뮤테이션 실행

useMutation 훅을 사용하여 데이터를 변경합니다.

import { gql, useMutation } from '@apollo/client';

const ADD_ITEM = gql`
  mutation AddItem($name: String!) {
    addItem(name: $name) {
      id
      name
    }
  }
`;

function AddItemForm() {
  let input;
  const [addItem, { data, loading, error }] = useMutation(ADD_ITEM);

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          addItem({ variables: { name: input.value } });
          input.value = '';
        }}
      >
        <input
          ref={node => {
            input = node;
          }}
        />
        <button type="submit">항목 추가</button>
      </form>
      {loading && <p>처리 중...</p>}
      {error && <p>오류: {error.message}</p>}
    </div>
  );
}

캐시 구성

InMemoryCache를 사용하여 캐시 정책을 설정합니다.

import { InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        items: {
          merge(existing, incoming) {
            return incoming;
          }
        }
      }
    }
  }
});

로컬 상태 관리

반응형 변수를 사용하여 로컬 상태를 관리합니다.

import { makeVar } from '@apollo/client';

export const cartItemsVar = makeVar([]);
export const isLoggedInVar = makeVar(false);

컴포넌트에서 사용:

import { useReactiveVar } from '@apollo/client';
import { cartItemsVar } from './cache';

function Cart() {
  const cartItems = useReactiveVar(cartItemsVar);

  return (
    <div>
      <h2>장바구니</h2>
      {cartItems.length === 0 ? (
        <p>장바구니가 비어 있습니다.</p>
      ) : (
        <ul>
          {cartItems.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

오류 처리

onError 링크를 사용하여 전역 오류를 처리합니다.

import { ApolloClient, InMemoryCache, from } from '@apollo/client';
import { onError } from '@apollo/client/link/error';

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) =>
      console.log(`[GraphQL 오류]: 메시지: ${message}, 위치: ${locations}, 경로: ${path}`)
    );
  }
  if (networkError) {
    console.log(`[네트워크 오류]: ${networkError}`);
  }
});

const client = new ApolloClient({
  link: from([errorLink, httpLink]),
  cache: new InMemoryCache()
});

성능 최적화

  • 필요한 필드만 요청하세요.
  • 쿼리 결과를 효율적으로 캐시하기 위해 id 필드를 포함하세요.
  • 자주 변경되지 않는 데이터에는 useQuery의 pollInterval 옵션을 사용하세요.
  • 큰 리스트에는 fetchMore를 사용한 페이지네이션을 고려하세요.

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

apollographql/apollo-connectors

Guide for integrating REST APIs into GraphQL supergraphs using Apollo Connectors with @source and @connect directives. Use this skill when the user: (1) mentions "connectors", "Apollo Connectors", or "REST Connector", (2) wants to integrate a REST API into GraphQL, (3) references @source or @connect directives, (4) works with files containing "# Note to AI Friends: This is an Apollo Connectors schema".

apollographql/apollo-federation

Guide for authoring Apollo Federation subgraph schemas. Use this skill when: (1) creating new subgraph schemas for a federated supergraph, (2) defining or modifying entities with @key, (3) sharing types/fields across subgraphs with @shareable, (4) working with federation directives (@external, @requires, @provides, @override, @inaccessible), (5) troubleshooting composition errors, (6) any task involving federation schema design patterns.

apollographql/apollo-mcp-server

Guide for using Apollo MCP Server to connect AI agents with GraphQL APIs. Use this skill when: (1) setting up or configuring Apollo MCP Server, (2) defining MCP tools from GraphQL operations, (3) using introspection tools (introspect, search, validate, execute), (4) troubleshooting MCP server connectivity or tool execution issues.

apollographql/apollo-router

Version-aware guide for configuring and running Apollo Router for federated GraphQL supergraphs. Generates correct YAML for both Router v1.x and v2.x. Use this skill when: (1) setting up Apollo Router to run a supergraph, (2) configuring routing, headers, or CORS, (3) implementing custom plugins (Rhai scripts or coprocessors), (4) configuring telemetry (tracing, metrics, logging), (5) troubleshooting Router performance or connectivity issues.

apollographql/apollo-server

Guide for building GraphQL servers with Apollo Server 5.x. Use this skill when: (1) setting up a new Apollo Server project, (2) writing resolvers or defining GraphQL schemas, (3) implementing authentication or authorization, (4) creating plugins or custom data sources, (5) troubleshooting Apollo Server errors or performance issues.

apollographql/graphql-operations

Guide for writing GraphQL operations (queries, mutations, fragments) following best practices. Use this skill when: (1) writing GraphQL queries or mutations, (2) organizing operations with fragments, (3) optimizing data fetching patterns, (4) setting up type generation or linting, (5) reviewing operations for efficiency.

apollographql/graphql-schema

Guide for designing GraphQL schemas following industry best practices. Use this skill when: (1) designing a new GraphQL schema or API, (2) reviewing existing schema for improvements, (3) deciding on type structures or nullability, (4) implementing pagination or error patterns, (5) ensuring security in schema design.

apollographql/rover

Guide for using Apollo Rover CLI to manage GraphQL schemas and federation. Use this skill when: (1) publishing or fetching subgraph/graph schemas, (2) composing supergraph schemas locally or via GraphOS, (3) running local supergraph development with rover dev, (4) validating schemas with check and lint commands, (5) configuring Rover authentication and environment, (6) exploring or searching a graph's schema for agent-driven discovery (rover schema describe / rover schema search).

apollographql/rust-best-practices

Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when: (1) writing new Rust code or functions, (2) reviewing or refactoring existing Rust code, (3) deciding between borrowing vs cloning or ownership patterns, (4) implementing error handling with Result types, (5) optimizing Rust code for performance, (6) writing tests or documentation for Rust projects.

관련 스킬