Communityコーディング&開発github.com

jezweb/react-hook-form-zod

React Hook Form v7 と Zod v4 を使用して、型安全でバリデーション付きのフォームを構築します。単一のスキーマがクライアントとサーバーの両方で動作し、z.infer による完全な TypeScript 推論を提供します。フォーム、マルチステップウィザードの構築、または制御されていない警告、リゾルバエラー、useFieldArray の問題、大規模フォームのパフォーマンス問題の修正に使用します。

react-hook-form-zod とは?

このスキルは、React Hook Form v7 と Zod v4 を統合して、型安全でバリデーションされたフォームを構築するための実践的なガイドです。単一の Zod スキーマを定義するだけで、クライアントとサーバーの両方でバリデーションロジックを共有でき、z.infer を使用することで TypeScript の完全な型推論が得られます。このスキルは、複雑なフォーム、マルチステップウィザード、大規模なフォームアプリケーションの開発に特に有用で、制御されていないコンポーネントの警告、リゾルバエラー、useFieldArray の不具合、パフォーマンス問題などの一般的な問題を解決する方法を提供します。また、テキスト入力、セレクトボックス、チェックボックス、配列入力などの様々なフィールドタイプの実装例、フォーム状態のリセットとエラーハンドリング、react-hook-form の useFieldArray を使用した動的配列入力の実装、そして useFormContext を活用した複雑なフォーム構造の管理についても詳しく説明しています。

対応~Claude Code~Codex CLI~Cursor
Part ofReact
npx skills add https://github.com/jezweb/claude-skills/tree/main/skills/react-hook-form-zod

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

react-hook-form-zod は何をしますか?

React Hook Form v7 と Zod v4 を使用して、型安全でバリデーション付きのフォームを構築します。単一のスキーマがクライアントとサーバーの両方で動作し、z.infer による完全な TypeScript 推論を提供します。フォーム、マルチステップウィザードの構築、または制御されていない警告、リゾルバエラー、useFieldArray の問題、大規模フォームのパフォーマンス問題の修正に使用します。

インストール

npm install react-hook-form @hookform/resolvers zod

基本的な使用方法

1. Zod スキーマを定義する

import { z } from 'zod';

export const userSchema = z.object({
  name: z.string().min(2, '名前は2文字以上必要です'),
  email: z.string().email('有効なメールアドレスを入力してください'),
  age: z.coerce.number().int().min(18, '18歳以上である必要があります'),
});

2. React Hook Form で使用する

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const formSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
});

type FormData = z.infer<typeof formSchema>;

export default function MyForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(formSchema),
  });

  const onSubmit = (data: FormData) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} />
      {errors.name && <p>{errors.name.message}</p>}

      <input {...register('email')} />
      {errors.email && <p>{errors.email.message}</p>}

      <button type="submit">送信</button>
    </form>
  );
}

詳細な使用法

フィールドタイプ

  • テキスト入力: z.string().min().max().email()
  • 数値入力: z.coerce.number().int().min().max()
  • セレクト: z.enum() または z.string() に .refine() を組み合わせる
  • チェックボックス: z.boolean()
  • 配列: z.array() を useFieldArray と一緒に使用

スキーマの共有

// shared/schema.ts
export const userSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
});

// client/Form.tsx
import { userSchema } from '../shared/schema';

// server/api.ts
import { userSchema } from '../shared/schema';

app.post('/api/users', async (req, res) => {
  const result = userSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json(result.error);
  }
  // データベースに保存...
});

マルチステップフォーム(ウィザード)

const step1Schema = z.object({ name: z.string().min(2) });
const step2Schema = z.object({ email: z.string().email() });
const step3Schema = z.object({ age: z.coerce.number().int().min(18) });

// 各ステップは独自の useForm インスタンスを持ち、完了時にデータを集約します

useFieldArray による配列入力

import { useFieldArray } from 'react-hook-form';

const formSchema = z.object({
  items: z.array(z.object({
    name: z.string().min(1),
    quantity: z.coerce.number().int().min(1),
  })).min(1, '少なくとも1つのアイテムが必要です'),
});

type FormData = z.infer<typeof formSchema>;

function ItemsForm() {
  const { control, register } = useForm<FormData>({
    resolver: zodResolver(formSchema),
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'items',
  });

  return (
    <form>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input {...register(`items.${index}.name` as const)} />
          <input type="number" {...register(`items.${index}.quantity` as const)} />
          <button type="button" onClick={() => remove(index)}>削除</button>
        </div>
      ))}
      <button type="button" onClick={() => append({ name: '', quantity: 1 })}>
        アイテムを追加
      </button>
    </form>
  );
}

エラーハンドリング

const { formState: { errors } } = useForm<FormData>({
  resolver: zodResolver(formSchema),
});

// 特定のフィールドのエラーを表示
{errors.name && <span className="error">{errors.name.message}</span>}

// すべてのエラーをまとめて表示
{Object.entries(errors).map(([field, error]) => (
  <p key={field}>{field}: {error.message}</p>
))}

パフォーマンスの最適化

  • 大規模フォームの場合は useFormContext を使用してプロップのドリルダウンを避ける
  • フィールドを論理的なグループに分割する
  • Zod スキーマで z.coerce を使用して、不必要な再レンダリングを避ける

useFormContext の例

import { useFormContext } from 'react-hook-form';

function NameField() {
  const { register, formState: { errors } } = useFormContext<FormData>();
  return (
    <div>
      <input {...register('name')} />
      {errors.name && <p>{errors.name.message}</p>}
    </div>
  );
}

// 親フォームは useFormContext をプロバイダーとして提供します

一般的な問題の修正

  • 制御されていない警告: controlled プロパティが一貫していることを確認し、null のデフォルト値を避ける
  • リゾルバエラー: Zod スキーマが @hookform/resolvers で必要な正しい型をエクスポートしていることを確認する
  • useFieldArray の問題: 動的配列キーには常に field.id を使用し、配列のインデックスは使用しない
  • パフォーマンスの問題: フィールドを分離し、useWatch の代わりに watch を使い、必要な場合にのみコンポーネントをラップする

Individual skills in this repo

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

jezweb/ai-image-generator

Generate AI images using Gemini or GPT APIs directly. Covers model selection (Gemini for scenes; GPT Image 2 for text rendering, batch variations, multi-reference compositing; GPT Image 1.5 for transparent icons), the 5-part prompting framework, API calling patterns, multi-turn editing, and quality assurance. Produces photorealistic scenes, icons, illustrations, OG images, posters, infographics, and product shots. Use when building websites that need images, creating marketing assets, or generating visual content. Triggers: 'generate image', 'ai image', 'create hero image', 'make an icon', 'generate illustration', 'create og image', 'poster', 'infographic', 'image variations', 'gpt-image-2', 'ai art', 'image generation'.

jezweb/aussie-business-english

Australian business English writing style for professional communications — warm, direct, EN-AU spelling (colour, organise, centre). Use whenever the user is writing for an Australian audience: emails, chat messages, proposals, client communications, blog posts, web copy, or any business writing. Apply to drafting, editing, and tone-checking professional text.

jezweb/claude-skills

Generate project documentation from codebase analysis — ARCHITECTURE.md, API_ENDPOINTS.md, DATABASE_SCHEMA.md. Reads source code, schema files, routes, and config to produce accurate, structured docs. Use when starting a project, onboarding contributors, or when docs are missing or stale. Triggers: 'generate docs', 'document architecture', 'create api docs', 'document schema', 'project documentation', 'write architecture doc'.

jezweb/claude-skills

Agent skill at plugins/social-media/skills/social-media-posts/SKILL.md

jezweb/claude-skills

Generate a complete, deployable landing page from a brief. Produces a single self-contained HTML file with Tailwind CSS (via CDN), responsive design, dark mode, semantic HTML, and OG meta tags. Sections: hero with CTA, features, social proof, pricing (optional), FAQ, footer. Use when building a marketing page, product launch page, coming soon page, or any standalone landing page. Triggers: 'landing page', 'create a page', 'marketing page', 'launch page', 'coming soon page', 'one-page site'.

jezweb/cloudflare-worker-builder

Scaffold and deploy Cloudflare Workers with Hono routing, Vite plugin, and Static Assets. Describe project, scaffold structure, configure bindings, deploy. Use whenever the user wants to create a Worker project, set up Hono on Cloudflare, configure D1 / R2 / KV / Queues bindings, or troubleshoot Worker export syntax, API route conflicts, HMR issues, or deployment failures.

jezweb/color-palette

Generate complete, accessible colour palettes from a single brand hex. Produces 11-shade scale (50-950), semantic tokens, dark mode variants, Tailwind v4 CSS output, WCAG contrast checks. Use whenever the user supplies a brand hex and asks for a palette, mentions setting up a design system, wants Tailwind theme colours from a brand colour, or asks to check colour accessibility / contrast.

jezweb/d1-drizzle-schema

Generate Drizzle ORM schemas for Cloudflare D1 databases with correct D1-specific patterns. Produces schema files, migration commands, type exports, and DATABASE_SCHEMA.md documentation. Handles D1 quirks: foreign keys always enforced, no native BOOLEAN/DATETIME types, 100 bound parameter limit, JSON stored as TEXT. Use when creating a new database, adding tables, or scaffolding a D1 data layer.

jezweb/elevenlabs-agents

Build conversational AI voice agents on the ElevenLabs platform. Configure agent + tools + knowledge base, integrate SDK (React / React Native / Swift / JS / server-side), test, deploy. Use whenever the user mentions ElevenLabs, building a voice agent, an AI phone system, an AI receptionist, conversational AI, or troubleshooting deprecated @11labs packages, webhook errors, CSP violations, localhost allowlist, or tool parsing errors.

jezweb/fastapi

Build Python APIs with FastAPI, Pydantic v2, and SQLAlchemy 2.0 async. Covers project structure, JWT auth, validation, and database integration with uv package manager. Prevents 7 documented errors. Use when: creating Python APIs, implementing JWT auth, or troubleshooting 422 validation, CORS, async blocking, form data, background tasks, or OpenAPI schema errors.

jezweb/favicon-gen

Generate custom favicons from logos, text, or brand colours. Produces favicon.svg, favicon.ico, apple-touch-icon.png, icon-192/512.png, and web manifest. Use whenever the user wants a favicon, mentions replacing a CMS default favicon, converting a logo into a favicon, creating branded initials icons, or troubleshooting favicon not displaying / iOS black square / missing manifest.

jezweb/github-release

Prepare and publish GitHub releases. Sanitizes code for public release (secrets scan, personal artifacts, LICENSE/README validation), creates version tags, and publishes via gh CLI. Trigger with 'release', 'publish', 'open source', 'prepare for release', 'create release', or 'github release'.

jezweb/google-apps-script

Build Google Apps Script automation for Sheets and Workspace. Custom menus, triggers (onEdit / time-driven / form submit), dialogs, sidebars, email batches, PDF export, external API. Use whenever the user wants to automate a Google Sheet, build a Sheets menu / sidebar / dialog, hit a Sheets row from email or a webhook, schedule a Sheets workflow, or asks 'how do I script this in Sheets'.

jezweb/google-chat-messages

Send Google Chat messages via incoming webhooks — text, rich cards (cardsV2), threaded replies. TypeScript types, card builder utility, widget reference inline. Use whenever the user wants to post to Google Chat from a script, build a chatbot reply, send a notification card, build a Google Chat webhook integration, or troubleshoot card / threading issues.

jezweb/hono-api-scaffolder

Scaffold Hono API routes for Cloudflare Workers. Produces route files, middleware, typed bindings, Zod validation, error handling, and API_ENDPOINTS.md documentation. Use after a project is set up with cloudflare-worker-builder or vite-flare-starter, when you need to add API routes, create endpoints, or generate API documentation.

jezweb/icon-set-generator

Generate cohesive, project-specific SVG icon sets for websites and applications. Use this skill whenever the user needs custom icons, an icon set for a website or app, icons for a client project, or mentions needing SVG icons that look consistent together. Also trigger when the user describes a project and icons would naturally be part of the deliverable — e.g. 'I'm building a site for a plumber' implies they'll need service icons. Trigger on: 'icons for', 'icon set', 'custom icons', 'SVG icons', 'make me icons', 'I need icons', 'website icons', 'project icons', or any request for consistent visual assets for a web project. Produces individual SVG files with a consistent style engine, not generic icon library lookups.

jezweb/image-processing

Process images for web development — resize, crop, trim whitespace, convert formats (PNG/WebP/JPG), optimise file size, generate thumbnails, create OG card images. Uses Pillow (Python) — no ImageMagick needed. Trigger with 'resize image', 'convert to webp', 'trim logo', 'optimise images', 'make thumbnail', 'create OG image', 'crop whitespace', 'process image', or 'image too large'.

jezweb/mcp-builder

Build MCP servers in Python with FastMCP. Define tools / resources / prompts, build the server, test locally, deploy to FastMCP Cloud or Docker. Use whenever the user mentions building an MCP server, exposing tools to LLMs, FastMCP, building a Claude integration, or troubleshooting FastMCP module-level server, storage, lifespan, middleware, OAuth, or deployment errors.

jezweb/nextjs

Build Next.js 16 apps with App Router, Server Components/Actions, Cache Components ("use cache"), and async route params. Includes proxy.ts and React 19.2. Prevents 25 documented errors. Use when: building Next.js 16 projects, or troubleshooting async params (Promise types), "use cache" directives, parallel route 404s, Turbopack issues, i18n caching, navigation throttling.

jezweb/project-health

All-in-one project configuration and health management. Sets up new projects (settings.local.json, CLAUDE.md, .gitignore), audits existing projects (permissions, context quality, MCP coverage, leaked secrets, stale docs), tidies accumulated cruft, captures session learnings, and adds permission presets. Uses sub-agents for heavy analysis to keep main context clean. Trigger with 'project health', 'check project', 'setup project', 'kickoff', 'bootstrap', 'tidy permissions', 'clean settings', 'capture learnings', 'audit context', 'add python permissions', or 'init project'.

関連スキル