jpskill.com
🛠️ 開発・MCP コミュニティ

web-server-state-react-query

React Queryでサーバーの状態を効率的に管理し、OpenAPIの定義から型安全なデータ取得を可能にするReactのWebアプリケーション開発を支援するSkill。

📜 元の英語説明(参考)

React Query server state, hey-api OpenAPI codegen, type-safe data fetching

🇯🇵 日本人クリエイター向け解説

一言でいうと

React Queryでサーバーの状態を効率的に管理し、OpenAPIの定義から型安全なデータ取得を可能にするReactのWebアプリケーション開発を支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o web-server-state-react-query.zip https://jpskill.com/download/10303.zip && unzip -o web-server-state-react-query.zip && rm web-server-state-react-query.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10303.zip -OutFile "$d\web-server-state-react-query.zip"; Expand-Archive "$d\web-server-state-react-query.zip" -DestinationPath $d -Force; ri "$d\web-server-state-react-query.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して web-server-state-react-query.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → web-server-state-react-query フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

React Query + hey-api のパターン

クイックガイド: hey-api を使用して OpenAPI 仕様から型安全な React Query hooks を生成します。カスタムの query hooks や手動の型定義を記述する必要はありません。生成された query options (getFeaturesOptions() パターン) と生成された型を使用します。環境変数を使用してクライアントを一度構成します。すべてのタイムアウト/リトライは名前付き定数を使用します。


<critical_requirements>

重要: この Skill を使用する前に

すべてのコードは CLAUDE.md のプロジェクト規約に従う必要があります (kebab-case, 名前付きエクスポート, インポート順, import type, 名前付き定数)

(必ず hey-api から生成された query options を使用してください -- カスタムの React Query hooks を記述しないでください)

(OpenAPI スキーマが変更された場合は、必ずクライアントコードを再生成してください)

(すべてのタイムアウト/リトライ値に名前付き定数を使用してください -- マジックナンバーは使用しないでください)

(API クライアントのベース URL は環境変数を使用して構成してください)

</critical_requirements>


自動検出: OpenAPI schema, hey-api, openapi-ts, 生成された React Query hooks, query options, getFeaturesOptions, useQuery, useMutation, QueryClient, QueryClientProvider, staleTime, gcTime, queryKey

使用する場面:

  • hey-api を使用して OpenAPI 仕様から型安全な API クライアントを生成する場合
  • 生成された React Query の query options をコンポーネントで使用する場合
  • QueryClient のデフォルト値、エラー処理、リトライポリシーを構成する場合
  • クエリのデバウンス、依存関係/条件付きフェッチの処理

使用しない場面:

  • OpenAPI spec が利用できない場合 (作成するか、tRPC の使用を検討してください)
  • GraphQL API (GraphQL クライアントを使用してください)
  • リアルタイム WebSocket API (WebSocket ソリューションを使用してください)
  • React Query のオーバーヘッドが正当化されない単純な一回限りのフェッチ

<philosophy>

Philosophy

OpenAPI-first の開発は、API コントラクトの唯一の信頼できる情報源を保証します。hey-api コードジェネレーター (@hey-api/openapi-ts) は、OpenAPI スキーマを完全に型付けされたクライアントコード、React Query hooks、および query options に変換し、手動の型定義を排除し、バグを減らします。

コア原則:

  1. 唯一の信頼できる情報源 -- OpenAPI スキーマが型、クライアントコード、およびモックを駆動します
  2. 手動での型付けはゼロ -- 生成されたコードは型のずれを排除します
  3. 一貫したパターン -- すべての API 呼び出しは、生成された query options を使用し、カスタム hooks は使用しません
  4. 集中管理された構成 -- クライアントの動作を構成する場所は 1 つ

</philosophy>


<patterns>

コアパターン

パターン 1: hey-api コード生成

OpenAPI spec から TypeScript クライアントコードと React Query hooks を生成するように @hey-api/openapi-ts を構成します。v0.73.0 以降、クライアントパッケージはバンドルされています。個別のインストールは不要です。

// openapi-ts.config.ts
import { defineConfig } from "@hey-api/openapi-ts";

export default defineConfig({
  input: "./openapi.yaml",
  output: "src/api-client",
  plugins: [
    "@hey-api/typescript",
    "@hey-api/sdk",
    "@tanstack/react-query",
    // "@hey-api/client-fetch" -- optional, Fetch is the default client since v0.73
  ],
});

重要なポイント: @hey-api/typescript は型を生成し (名前が @hey-api/types から変更されました)、@hey-api/sdk はサービス関数を生成します (名前が @hey-api/services から変更されました)。Fetch クライアントは v0.73 以降デフォルトでバンドルされています。オプションをカスタマイズするには、@hey-api/client-fetch を明示的に追加するだけです。npx openapi-ts を使用して生成を実行するか、ビルドスクリプトとして追加します。

生成された出力構造と使用法については、examples/core.md パターン 1 を参照してください。


パターン 2: クライアント構成

API クライアントのベース URL と QueryClient のデフォルト値をプロバイダーコンポーネントで 一度 構成します。コードを変更せずに環境全体で動作するように、ベース URL には環境変数を使用します。

const FIVE_MINUTES_MS = 5 * 60 * 1000;

// プロバイダーコンポーネント内:
const [queryClient] = useState(
  () =>
    new QueryClient({
      defaultOptions: {
        queries: { staleTime: FIVE_MINUTES_MS, refetchOnWindowFocus: false },
      },
    }),
);

client.setConfig({ baseUrl: process.env.API_BASE_URL ?? "" });

重要なポイント: hey-apiclient.setConfig() は既存の構成とマージされます (置き換えません)。すべての時間値に名前付き定数を使用します。auth オプションを設定するか、認証ヘッダーにインターセプターを使用します。

完全なプロバイダーの設定と認証の構成については、examples/core.md パターン 2 を参照してください。


パターン 3: 生成された Query Options の使用

生成された query options を直接使用します -- カスタムの React Query hooks を記述しないでください。Options は完全に型付けされており、生成された query keys が含まれています。

import { useQuery } from "@tanstack/react-query";
import { getFeaturesOptions } from "./api-client/@tanstack/react-query.gen";

// 直接使用 -- 完全に型付けされています
const { data, isPending, error } = useQuery(getFeaturesOptions());

// オーバーライドあり -- スプレッドしてカスタマイズ
const TEN_MINUTES_MS = 10 * 60 * 1000;
const { data } = useQuery({
  ...getFeaturesOptions(),
  staleTime: TEN_MINUTES_MS,
  enabled: someCondition,
});

良い理由: ボイラープレートがゼロ、型安全、一貫したパターン、query keys が自動的に名前空間化される、スプレッドすることで簡単にカスタマイズできる

コンポーネントの例と避けるべき悪いパターンについては、examples/core.md パターン 3 を参照してください。


パターン 4: エラー処理

React Query v5 では、useQuery から onError / onSuccess / onSettled コールバックが削除されました。コンポーネントレベルの isPending / error 状態、エラーの副作用に対する useEffect、または QueryCache / MutationCache を介したグローバルハンドラーを使用します。

// グローバルエラー処理 (v5 パターン)
new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      if (query.state.data !== undefined) {
        showNotification(`Something went wrong: ${error.message}`);
      }
    },
  }),
  mutationCache: new MutationCache({
    onError: (error) => {
      showNotification("Operation failed. Please try again.");
    },
  }),
});

コンポーネントレベルの処理、指数バックオフによるリトライ、およびエラー境界については、examples/error-handling.md を参照してください。


パターン 5: デバウンスされたクエリ

検索/フィルタークエリをデバウンスします

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

React Query + hey-api Patterns

Quick Guide: Generate type-safe React Query hooks from OpenAPI specs using hey-api. Never write custom query hooks or manual type definitions -- use generated query options (getFeaturesOptions() pattern) and generated types. Configure the client once via environment variables. All timeouts/retries use named constants.


<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST use generated query options from hey-api -- NEVER write custom React Query hooks)

(You MUST regenerate client code when OpenAPI schema changes)

(You MUST use named constants for ALL timeout/retry values -- NO magic numbers)

(You MUST configure API client base URL via environment variables)

</critical_requirements>


Auto-detection: OpenAPI schema, hey-api, openapi-ts, generated React Query hooks, query options, getFeaturesOptions, useQuery, useMutation, QueryClient, QueryClientProvider, staleTime, gcTime, queryKey

When to use:

  • Generating type-safe API client from OpenAPI specs with hey-api
  • Using generated React Query query options in components
  • Configuring QueryClient defaults, error handling, retry policies
  • Debouncing queries, handling dependent/conditional fetching

When NOT to use:

  • No OpenAPI spec available (consider writing one or using tRPC)
  • GraphQL API (use a GraphQL client)
  • Real-time WebSocket APIs (use a WebSocket solution)
  • Simple one-off fetches where React Query overhead isn't justified

<philosophy>

Philosophy

OpenAPI-first development ensures a single source of truth for your API contract. The hey-api code generator (@hey-api/openapi-ts) transforms your OpenAPI schema into fully typed client code, React Query hooks, and query options -- eliminating manual type definitions and reducing bugs.

Core Principles:

  1. Single source of truth -- OpenAPI schema drives types, client code, and mocks
  2. Zero manual typing -- Generated code eliminates type drift
  3. Consistent patterns -- All API calls use generated query options, never custom hooks
  4. Centralized configuration -- One place to configure client behavior

</philosophy>


<patterns>

Core Patterns

Pattern 1: hey-api Code Generation

Configure @hey-api/openapi-ts to generate TypeScript client code and React Query hooks from your OpenAPI spec. Since v0.73.0, client packages are bundled -- no separate installation needed.

// openapi-ts.config.ts
import { defineConfig } from "@hey-api/openapi-ts";

export default defineConfig({
  input: "./openapi.yaml",
  output: "src/api-client",
  plugins: [
    "@hey-api/typescript",
    "@hey-api/sdk",
    "@tanstack/react-query",
    // "@hey-api/client-fetch" -- optional, Fetch is the default client since v0.73
  ],
});

Key points: @hey-api/typescript generates types (renamed from @hey-api/types), @hey-api/sdk generates service functions (renamed from @hey-api/services). Fetch client is bundled by default since v0.73 -- only add @hey-api/client-fetch explicitly to customize its options. Run generation via npx openapi-ts or add as a build script.

See examples/core.md Pattern 1 for generated output structure and usage.


Pattern 2: Client Configuration

Configure the API client base URL and QueryClient defaults once in a provider component. Use environment variables for the base URL so it works across environments without code changes.

const FIVE_MINUTES_MS = 5 * 60 * 1000;

// In your provider component:
const [queryClient] = useState(
  () =>
    new QueryClient({
      defaultOptions: {
        queries: { staleTime: FIVE_MINUTES_MS, refetchOnWindowFocus: false },
      },
    }),
);

client.setConfig({ baseUrl: process.env.API_BASE_URL ?? "" });

Key points: hey-api's client.setConfig() merges with existing config (doesn't replace). Named constants for all time values. Set auth option or use interceptors for auth headers.

See examples/core.md Pattern 2 for full provider setup and auth configuration.


Pattern 3: Using Generated Query Options

Use generated query options directly -- never write custom React Query hooks. Options are fully typed and include generated query keys.

import { useQuery } from "@tanstack/react-query";
import { getFeaturesOptions } from "./api-client/@tanstack/react-query.gen";

// Direct usage -- fully typed
const { data, isPending, error } = useQuery(getFeaturesOptions());

// With overrides -- spread and customize
const TEN_MINUTES_MS = 10 * 60 * 1000;
const { data } = useQuery({
  ...getFeaturesOptions(),
  staleTime: TEN_MINUTES_MS,
  enabled: someCondition,
});

Why good: Zero boilerplate, type-safe, consistent patterns, query keys auto-namespaced, easy to customize by spreading

See examples/core.md Pattern 3 for component examples and bad patterns to avoid.


Pattern 4: Error Handling

React Query v5 removed onError/onSuccess/onSettled callbacks from useQuery. Use component-level isPending/error states, useEffect for error side effects, or global handlers via QueryCache/MutationCache.

// Global error handling (v5 pattern)
new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      if (query.state.data !== undefined) {
        showNotification(`Something went wrong: ${error.message}`);
      }
    },
  }),
  mutationCache: new MutationCache({
    onError: (error) => {
      showNotification("Operation failed. Please try again.");
    },
  }),
});

See examples/error-handling.md for component-level handling, retry with exponential backoff, and error boundaries.


Pattern 5: Debounced Queries

Debounce search/filter queries to prevent excessive API calls on every keystroke.

const DEBOUNCE_DELAY_MS = 500;
const MIN_SEARCH_LENGTH = 0;

const debouncedTerm = useDebounce(searchTerm, DEBOUNCE_DELAY_MS);
const { data } = useQuery({
  queryKey: ["search", debouncedTerm],
  queryFn: () => searchAPI(debouncedTerm),
  enabled: debouncedTerm.length > MIN_SEARCH_LENGTH,
});

Why good: Prevents excessive API calls, query key includes debounced term for proper cache management, enabled prevents empty queries

</patterns>


Detailed Resources:


<red_flags>

RED FLAGS

High Priority Issues:

  • Writing custom React Query hooks instead of using generated query options -- creates inconsistent patterns and loses type safety
  • Manual TypeScript interfaces for API responses -- drift from OpenAPI schema causes runtime errors
  • Magic numbers for timeouts/retries -- use named constants (FIVE_MINUTES_MS, MAX_RETRY_ATTEMPTS)
  • Hardcoded API URLs -- use environment variables for multi-environment deploys
  • Using onError/onSuccess callbacks on useQuery -- removed in React Query v5

Medium Priority Issues:

  • Mutating global client config inside query functions -- causes race conditions in concurrent requests
  • Missing error boundaries -- unhandled query errors crash entire component tree
  • retry: true in development with mocks -- should be false to fail fast
  • Not cleaning up AbortController timeouts -- memory leak

Gotchas & Edge Cases:

  • cacheTime was renamed to gcTime in v5 (garbage collection time)
  • isLoading was renamed to isPending in v5
  • keepPreviousData replaced with placeholderData: (prev) => prev
  • useInfiniteQuery now requires initialPageParam option
  • Server-side retry defaults to 0 in v5 (was 3 in v4)
  • client.setConfig() merges with existing config, doesn't replace it
  • Generated query keys are immutable tuples (safe for React Query key equality)
  • Fetch timeout is different from React Query's staleTime/gcTime
  • Generated types change when OpenAPI schema changes -- commit generated files to catch breaking changes in review
  • React Query v5 requires React 18.0+

</red_flags>


<critical_reminders>

CRITICAL REMINDERS

All code must follow project conventions in CLAUDE.md

(You MUST use generated query options from hey-api -- NEVER write custom React Query hooks)

(You MUST regenerate client code when OpenAPI schema changes)

(You MUST use named constants for ALL timeout/retry values -- NO magic numbers)

(You MUST configure API client base URL via environment variables)

Failure to follow these rules will cause type drift, inconsistent patterns, and production bugs.

</critical_reminders>