К основному содержанию
скилл CX Codex

react-hook-form-audit — скилл для Claude Code: аудит антипаттернов RHF

Скилл react-hook-form-audit ищет 16 антипаттернов React Hook Form в проекте Next.js на App Router и пишет markdown-отчёт с номерами строк. Только чтение, код не меняет.

MIT 158 установок ★ 227 обновлён 2026-08-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pproenca/dot-skills --skill react-hook-form-audit -a claude-code
Открыть на GitHub

Что делает react-hook-form-audit

Скилл прогоняет по коду две проверки. Быстрая ищет регулярками через rg, структурная разбирает AST через ts-morph. Всего 16 детекторов по четырём уровням: от watch() в том же компоненте, что и useForm(), до useEffect с reset(data) вместо пропа values и useFieldArray({ disabled }), который молча гасит мутации. Список правил лежит в references/detectors.md.

Запуск: bash scripts/audit.sh, при необходимости с --project /path/to/nextjs-app или --dry-run, чтобы посмотреть результат без записи файла. На выходе — .rhf-audit-report.md в корне проекта: находки сгруппированы по severity, у каждой ссылка file:line и переход к правилу в соседнем скилле react-hook-form. Код возврата 1 при CRITICAL/HIGH, поэтому отчёт годится как гейт в CI.

Нужны rg, node ≥ 18 с npm и jq — без любого из них audit.sh упадёт с кодом 2 и отчёта не будет. ts-morph при первом запуске ставится в scripts/node_modules/, проект не трогает. Шумные детекторы правятся через include_globs и exclude_globs в config.json.

Какие задачи решает

  • найти формы, которые перерисовываются на каждый ввод
  • проверить новый RHF-код до ревью PR
  • поймать импорт RHF в файле без "use client"
  • уронить CI, когда форма нарушает правило уровня CRITICAL
  • разобрать, почему useFieldArray не обновляет список

Примеры запросов агенту

  • Прогони аудит React Hook Form в этом Next.js проекте и покажи только находки уровня CRITICAL.
  • Проверь формы на антипаттерны RHF, отчёт положи в корень проекта.
  • Сделай --dry-run аудит форм, хочу увидеть находки без файла отчёта.

Как установить react-hook-form-audit

1Через Skills CLI (Vercel)

npx skills add pproenca/dot-skills --skill react-hook-form-audit -a claude-code

2Вручную: положить файлы

~/.claude/skills/react-hook-form-audit/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/react-hook-form-audit/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о react-hook-form-audit

Как установить react-hook-form-audit в Claude Code?

Выполните npx skills add pproenca/dot-skills --skill react-hook-form-audit -a claude-code, после чего файл скилла появится по пути ~/.claude/skills/react-hook-form-audit/SKILL.md.

Что делает react-hook-form-audit?

Проверяет код Next.js App Router на антипаттерны React Hook Form и выдаёт markdown-отчёт с привязкой к строкам и ссылками на правила скилла react-hook-form.

Что нужно поставить перед первым запуском?

rg, node ≥ 18 с npm и jq. ts-morph скилл ставит сам при первом запуске в scripts/node_modules/, не затрагивая зависимости проекта.

Исходный текст

SKILL.md · MIT
---
name: react-hook-form-audit
description: Audits a Next.js (App Router, 14/15+) codebase for React Hook Form anti-patterns — watch() at form root, Controller inlined in parent, async submit without try/catch, missing setError on server failures, RHF in non-"use client" files, RHF mixed with useActionState, schemas defined inside components, useFieldArray without field.id keys, register({ disabled }) for visual disabling, useFieldArray({ disabled }) that silently no-ops mutations, useEffect+reset(data) instead of the values prop. Read-only; emits a markdown report with file:line citations linking back to the companion `react-hook-form` distillation skill. Trigger when the user asks to audit/review/lint RHF usage, find form anti-patterns, or run a quality check on forms — even if they don't say "react-hook-form" by name; if they mention auditing forms in a Next.js project, use this skill.
---
# React Hook Form Audit for Next.js

Static-analysis audit that detects 16 React Hook Form anti-patterns in Next.js App Router codebases. Combines ripgrep (fast pass for regex-detectable rules) with ts-morph (AST pass for structural rules). Outputs a markdown report grouped by severity, with file:line references and links back to the companion `react-hook-form` distillation skill.

## When to Apply

- User asks to audit, review, or lint React Hook Form usage in a Next.js project
- User reports symptoms like "the form re-renders too much" or "we have RHF bugs we can't pin down"
- Before a PR review of new RHF-heavy code
- As a CI gate (exit code 1 on CRITICAL/HIGH findings)
- After upgrading react-hook-form, to catch advice that drifted

## Tool Requirements

- `rg` (ripgrep) — install via `brew install ripgrep` or your package manager
- `node` ≥ 18 with `npm` — used to run the AST detectors via `ts-morph`
- `jq` — for JSON munging in the orchestrator

`ts-morph` is installed on first run into `scripts/node_modules/` (one-time, ~30s). The skill never touches the audited project's `node_modules`.

## Risk Level

**Read-only.** The skill reads source files and writes one markdown report (plus an optional JSON sidecar) to the audited project root. No git operations, no package mutations, no network calls.

## Workflow Overview

```
1. detect-project.sh   Verify Next.js + react-hook-form in package.json
2. collect-files.sh    Ripgrep for "use client" files importing RHF
3. detect-fast.sh      Ripgrep detectors (rules 5, 11, 14)
4. detect-ast.mjs      ts-morph detectors (rules 1-3, 6-10, 12-13, 15-17)
5. render-report.mjs   Render markdown + JSON; print summary; exit 0/1
```

See [`references/workflow.md`](references/workflow.md) for the per-step contract, error handling, and CI integration.

## Usage

```bash
# Audit the current directory
bash scripts/audit.sh

# Audit a specific project
bash scripts/audit.sh --project /path/to/nextjs-app

# Preview without writing the report file
bash scripts/audit.sh --dry-run
```

Exit codes:
- `0` — no CRITICAL or HIGH findings
- `1` — CRITICAL or HIGH findings exist
- `2` — environment or configuration error (missing tool, invalid project)

## Detector Catalog

16 detectors across 4 severities. See [`references/detectors.md`](references/detectors.md) for per-rule pattern, AST shape, false-positive notes, and the line of advice each detector enforces.

| ID | Severity | What it catches |
|----|---------|-----------------|
| 01 | CRITICAL | `watch()` in same component as `useForm()` |
| 02 | CRITICAL | `watch()` with no args (subscribes to all fields) |
| 03 | CRITICAL | `useForm()` without `defaultValues` |
| 05 | CRITICAL | RHF imported in a non-`"use client"` file |
| 06 | HIGH | `<Controller>` inlined inside `useForm()` parent |
| 07 | HIGH | Async submit handler without `try/catch` |
| 08 | HIGH | Validation schema defined inside the component |
| 09 | HIGH | Submit calls fetch/axios but never `setError('root.*')` |
| 10 | HIGH | RHF mixed with `useActionState` in same component |
| 11 | MEDIUM | `mode: 'onChange'` without explanatory comment |
| 12 | MEDIUM | `register({ disabled: <state> })` for visual disable |
| 13 | MEDIUM | `useFieldArray` map missing `field.id` as key |
| 14 | LOW | `reValidateMode: 'onBlur'` (now demoted advice) |
| 15 | LOW | `useFormContext()` usage (manual review) |
| 16 | MEDIUM | `useFieldArray({ disabled: <state> })` — silently no-ops every mutation |
| 17 | MEDIUM | `useEffect` + `reset(data)` instead of the `values` prop |

Rule 04 (`useEffect` depends on the `useForm` return) was **removed** in 0.2.0 — the premise was false. See [`references/detectors.md`](references/detectors.md).

## How to Use

1. Confirm project is a Next.js App Router app with react-hook-form installed (`detect-project.sh` will check)
2. Run `bash scripts/audit.sh [--project <path>]`
3. Read the generated `.rhf-audit-report.md` in the project root
4. For each finding, follow the link to the companion distillation rule for the fix
5. After fixing, re-run to verify a clean audit

If a detector is too noisy in your project, narrow `include_globs` / widen `exclude_globs` in `config.json` rather than disabling detectors — the catalog is small enough that each finding should be either a real issue or a documented exception worth a comment.

## Setup

The skill ships with sensible defaults in `config.json`. On first run, `audit.sh` will install `ts-morph` into `scripts/node_modules/`. Override settings by editing `config.json`:

- `project_root` — absolute path to the project (defaults to current directory)
- `report_path` / `json_report_path` — output filenames (relative to project root)
- `rule_link_base` — base URL or path for companion-rule links
- `include_globs` / `exclude_globs` — narrow the scan surface

## Reference Files

- [`references/workflow.md`](references/workflow.md) — detailed workflow, error handling, CI integration
- [`references/detectors.md`](references/detectors.md) — per-detector spec, AST shape, false-positive notes
- [`gotchas.md`](gotchas.md) — accumulated failure modes (append-only)

## Related Skills

- `react-hook-form` — the companion distillation skill with the 35 rules this auditor enforces. Findings link directly to its reference files.
- `react-19` — for Server Action / `useActionState` patterns the audit explicitly does NOT cover

© pproenca · MIT · pproenca/dot-skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
react-hook-form-zod ovachiever Скилл react-hook-form-zod учит агента собирать формы на React Hook Form с валидацией через Zod. Одна схема работает и на клиенте, и на сервере. CX Codex +1 725установок form-refactorer redpanda-data Скилл form-refactorer переписывает старые формы на компоненты Field из Redpanda UI Registry с валидацией через Zod и react-hook-form. CX Codex +1 1установок form-validation-architect curiositech Скилл form-validation-architect для Claude Code проектирует React-формы с проверкой через react-hook-form и Zod. Описывает многошаговые сценарии, динамические поля и асинхронную валидацию. CX Codex +1 205установок safe-action-forms next-safe-action Скилл safe-action-forms для Claude Code помогает связывать серверные экшены next-safe-action с веб-формами. Настраивает адаптер react-hook-form, нативные HTML-формы и загрузку файлов. CX Codex +1 1 300установок react-formengine-ai-form-builder-cursorrules-prompt-file PatrickJS Правило react-formengine-ai-form-builder-cursorrules-prompt-file для Cursor собирает React-формы по скриншоту, PDF, HTML или описанию и выдаёт схему FormEngine JSON и рабочий App.tsx. CX Codex +1 ★ 41 178звёзд репо form-validation aj-geddes Скилл form-validation для Claude Code помогает настроить валидацию форм в React и Vue с проверкой типов в TypeScript. Валидирует пошаговые формы и сразу показывает ошибки. CX Codex +1 507установок

Из того же набора139

Весь набор →
algorithmic-complexity-review Скилл algorithmic-complexity-review находит в коде причины роста времени и памяти: от вложенных циклов до N+1-запросов. Пригодится при ревью производительности и разборе медленных участков. CX Codex +1 171установок expo-ios-hig Скилл expo-ios-hig для Claude Code содержит правила Apple Human Interface Guidelines для экранов, списков и навигации в Expo и React Native. CX Codex +1 169установок web-taste Скилл web-taste для ИИ-агента: сначала разобраться, кто пользователь и чего он хочет от экрана, и только потом писать JSX на React 19 и Next.js 16 с Tailwind. CX Codex +1 169установок typescript-advanced-patterns Скилл typescript-advanced-patterns для Claude Code содержит 40 правил по продвинутому TypeScript: type-level программированию, API библиотек и возможностям TS 5.x. Углубляет паттерны typescript-refactor. CX Codex +1 162установок codex-goals Скилл codex-goals для Codex помогает формулировать и проверять долгосрочные цели: задавать измеримый результат, способ проверки и условие остановки. Описывает постановку многошаговых задач с понятным финалом. CX Codex +1 158установок expo-design-system Скилл expo-design-system для Claude Code помогает строить и проверять общие компоненты Expo и React Native для веба и iOS. Подключается при работе с токенами, темами и повторно используемым интерфейсом. CX Codex +1 156установок complexity-optimizer Скилл complexity-optimizer находит узкие места алгоритмической сложности в коде и готовит отчёт с безопасными исправлениями. CX Codex +1 156установок nextjs-bundle-optimizer Скилл nextjs-bundle-optimizer для Claude Code измеряет размер бандла и время сборки Next.js и помогает проверять оптимизации по одной. Проверяет оптимизации при росте First Load JS или замедлении сборки. CX Codex +1 152установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой