# React NativeとGraphQL 2026年版: Apollo Client、クエリ、面接対策 > Apollo Client 4.0を使用してReact NativeにGraphQLを統合する方法を解説します。クエリ、ミューテーション、キャッシュ戦略、モバイルGraphQL開発の面接質問についても詳しく説明します。 - Published: 2026-08-20 - Updated: 2026-08-20 - Author: Anthony Fillion-Maillet - Tags: react-native, graphql, apollo-client, mobile, api, interview - Reading time: 9 min --- GraphQLは、柔軟なデータ取得と効率的なネットワーク使用を必要とするReact Nativeアプリケーションにおいて、優先的なAPIレイヤーとなっています。2025年後半にリリースされたApollo Client 4.0は、モバイル環境向けに特別に設計された、20〜30%小さいバンドルサイズと改善されたTypeScriptサポートを備えた軽量アーキテクチャを提供します。 > **Apollo Client 4.0の主な変更点** > > Apollo Client 4.0では、React固有のエクスポートが`@apollo/client/react`に分離されました。React 19のSuspenseとReact Compilerをサポートし、モノリシックな`ApolloError`がデバッグ改善のための特定のエラークラスに置き換えられています。 ## React NativeでのApollo Client 4のセットアップ インストールプロセスはシンプルです。Apollo Client 4.0はExpoプロジェクトとベアReact Nativeプロジェクトの両方で動作します。 ```bash # Installation npm install @apollo/client graphql ``` クライアントの初期化には、ネットワークリクエスト用の`HttpLink`とローカル状態管理用の`InMemoryCache`が必要です。 ```typescript // src/apollo/client.ts import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'; const httpLink = new HttpLink({ uri: 'https://api.example.com/graphql', // Enable text streaming for @defer and subscriptions fetchOptions: { reactNative: { textStreaming: true }, }, }); export const apolloClient = new ApolloClient({ link: httpLink, cache: new InMemoryCache({ typePolicies: { Query: { fields: { // Merge paginated results products: { keyArgs: ['category'], merge(existing = [], incoming) { return [...existing, ...incoming]; }, }, }, }, }, }), }); ``` `typePolicies`の設定は、無限スクロールを持つモバイルアプリで一般的な要件であるページネーションデータのキャッシュ正規化を処理します。 ## ApolloProviderでアプリをラップする プロバイダーパターンはApollo ClientをReactコンポーネントツリーに接続します。通常は`App.tsx`またはExpo Routerのレイアウトでルートレベルに配置します。 ```tsx // App.tsx import { ApolloProvider } from '@apollo/client/react'; import { apolloClient } from './src/apollo/client'; import { RootNavigator } from './src/navigation'; export default function App() { return ( ); } ``` Apollo Client 4.0では、ReactフックはメインエントリポイントではなくApollo/client/react`からインポートします。この変更により、コアクライアントがReact以外のコンテキストで実行される場合のバンドルサイズが削減されます。 ## 型安全なGraphQLクエリの作成 GraphQL Code Generatorはスキーマから TypeScript型を生成し、実行時の型の不一致を排除します。クライアントプラグインと一緒にインストールします。 ```bash # Install codegen tools npm install -D @graphql-codegen/cli @graphql-codegen/client-preset ``` codegen設定はスキーマを指定し、出力場所を指定します。 ```typescript // codegen.ts import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { schema: 'https://api.example.com/graphql', documents: ['src/**/*.tsx', 'src/**/*.ts'], generates: { './src/gql/': { preset: 'client', config: { documentMode: 'string', }, }, }, }; export default config; ``` `npx graphql-codegen`を実行すると、`useQuery`フックが使用する型付きドキュメントノードが生成されます。 ## useQueryによるデータ取得 `useQuery`フックは、ローディング状態、エラー、キャッシュ更新を管理します。Apollo Client 4.0では、より予測可能な状態遷移のための`dataState` APIが導入されています。 ```tsx // src/screens/ProductListScreen.tsx import { useQuery } from '@apollo/client/react'; import { graphql } from '../gql'; import { ActivityIndicator, FlatList, Text, View } from 'react-native'; const GET_PRODUCTS = graphql(` query GetProducts($category: String!, $limit: Int, $offset: Int) { products(category: $category, limit: $limit, offset: $offset) { id name price imageUrl } } `); export function ProductListScreen({ category }: { category: string }) { const { data, loading, error, fetchMore } = useQuery(GET_PRODUCTS, { variables: { category, limit: 20, offset: 0 }, // Fetch from cache first, then network fetchPolicy: 'cache-and-network', // Keep previous data while fetching new notifyOnNetworkStatusChange: true, }); if (error) { return Error: {error.message}; } const loadMore = () => { fetchMore({ variables: { offset: data?.products.length ?? 0 }, }); }; return ( item.id} renderItem={({ item }) => } onEndReached={loadMore} onEndReachedThreshold={0.5} ListFooterComponent={loading ? : null} /> ); } ``` `cache-and-network`フェッチポリシーは、サーバーからのリフレッシュ中にキャッシュデータを即座に表示します。このパターンはモバイルネットワークでの体感遅延を軽減します。 ## ミューテーションと楽観的更新 ミューテーションはサーバーデータを変更し、ローカルキャッシュを更新します。楽観的レスポンスは、サーバーが変更を確認する前に即座のフィードバックを提供します。 ```tsx // src/hooks/useAddToCart.ts import { useMutation } from '@apollo/client/react'; import { graphql } from '../gql'; const ADD_TO_CART = graphql(` mutation AddToCart($productId: ID!, $quantity: Int!) { addToCart(productId: $productId, quantity: $quantity) { id items { id product { id name } quantity } totalPrice } } `); export function useAddToCart() { const [addToCart, { loading }] = useMutation(ADD_TO_CART, { // Optimistic response for instant UI feedback optimisticResponse: ({ productId, quantity }) => ({ addToCart: { __typename: 'Cart', id: 'current-cart', items: [], totalPrice: 0, }, }), // Update cache after mutation update(cache, { data }) { if (!data?.addToCart) return; cache.modify({ id: cache.identify({ __typename: 'Cart', id: 'current-cart' }), fields: { items: () => data.addToCart.items, totalPrice: () => data.addToCart.totalPrice, }, }); }, }); return { addToCart, loading }; } ``` `cache.modify`メソッドは、クエリ全体を再取得せずにキャッシュされたフィールドを直接更新します。このアプローチはセルラー接続でのネットワークリクエストを最小限に抑えます。 ## モバイルアプリでのネットワークエラー処理 Apollo Client 4.0では、汎用の`ApolloError`が特定のエラークラスに置き換えられています。静的な`.is()`メソッドにより、型安全なエラー処理が可能になります。 ```tsx // src/components/ErrorBoundary.tsx import { NetworkError, GraphQLErrors } from '@apollo/client/errors'; import { Text, Button, View } from 'react-native'; interface Props { error: Error; onRetry: () => void; } export function QueryErrorHandler({ error, onRetry }: Props) { // Network failure (offline, timeout, DNS) if (NetworkError.is(error)) { return ( Connection failed. Check your internet.