diff --git a/.agents/skills/frontend-design/LICENSE.txt b/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.agents/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..a533345 --- /dev/null +++ b/.agents/skills/frontend-design/SKILL.md @@ -0,0 +1,71 @@ +--- +name: frontend-design +description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. +license: Complete terms in LICENSE.txt +--- + +# Frontend Design + +Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified. + +## Ground your designs in the subject matter + +If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout. + +## Design principles + +For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option. + +Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct. + +Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content. + +Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif. + +Avoid these default typographic treatments; they are the commonest tells of a generated page: +- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color. +- Using all caps for labels. +- Adding unnecessary typographic labels above content. + +Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence. + +Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed. + +Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance. + +## Process: plan, review against the brief, build, critique + +For calibration, AI-generated design right now clusters around some traits: +1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell); +2. a near-black background with a single bright acid-green or vermilion accent; +3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns; +4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration; +5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text. + +All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn. + +Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles. +- Color: describe the core base palette as 4–6 named hex values. +- Type: the typefaces and their roles. +- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified? +- Principles: the high-level guidance for what makes this page unique. + +Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan. + +When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections. + +## Restraint and self-critique + +Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes. + +## More on writing in design + +Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience. + +Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever. + +Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around. + +Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act. + +Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job. diff --git a/.agents/skills/react-hook-form/AGENTS.md b/.agents/skills/react-hook-form/AGENTS.md new file mode 100644 index 0000000..a1e82a3 --- /dev/null +++ b/.agents/skills/react-hook-form/AGENTS.md @@ -0,0 +1,96 @@ +# React Hook Form + +**Version 2.1.0** +Community +July 2026 + +> **Note:** This document targets React Hook Form codebases. +> It is mainly for agents and LLMs to follow when maintaining, generating, or refactoring forms. +> Humans may also find it useful, but guidance here is optimized for automation and consistency +> by AI-assisted workflows. + +--- + +## Abstract + +Focused guide to the React Hook Form decisions a capable model gets wrong. Contains 35 rules across 7 categories, verified against react-hook-form 7.82.0 by diffing the shipped type definitions and type-checking every code block under tsc --strict against the real package types. Covers where a subscription must live to isolate re-renders, the third useForm generic that transforming resolvers require, the options that silently drop data from the submitted payload (register disabled, shouldUnregister, useFieldArray disabled), the NaN that valueAsNumber produces for an empty input, server error handling via setError('root.*'), resetDefaultValues() for rebasing the dirty baseline after a save, and the Watch / FormStateSubscribe / FieldArray render-prop components. Rules that merely restate what the library already does correctly have been removed. + +--- + +## Table of Contents + +1. [Form Configuration](references/_sections.md#1-form-configuration) — **CRITICAL** + - 1.1 [Always Provide defaultValues for Form Initialization](references/formcfg-default-values.md) — CRITICAL (prevents uncontrolled-to-controlled input warnings and a reset() with nothing to restore) + - 1.2 [Depend on formState Slices, Not on formState Itself](references/formcfg-useeffect-dependency.md) — HIGH (prevents effects that re-run on every keystroke) + - 1.3 [Justify Any mode Other Than the Default onSubmit](references/formcfg-validation-mode.md) — CRITICAL (prevents a full validation pass and re-render on every keystroke) + - 1.4 [Keep Default reValidateMode Unless Validation Is Expensive](references/formcfg-revalidate-mode.md) — MEDIUM (maintains immediate corrective feedback after first submit) + - 1.5 [Keep shouldUnregister Off Unless Hidden Fields Must Leave the Payload](references/formcfg-should-unregister.md) — HIGH (prevents silently dropping values the user already entered) + - 1.6 [Pass the Third useForm Generic When the Resolver Transforms Values](references/formcfg-transformed-values-generic.md) — CRITICAL (makes handleSubmit receive the schema's output type instead of its input type) + - 1.7 [Use Async defaultValues for Server Data](references/formcfg-async-default-values.md) — CRITICAL (eliminates manual useEffect reset patterns) + - 1.8 [Use the HTML disabled Attribute for Visual Disabling, Not register's disabled Option](references/formcfg-disabled-prop.md) — MEDIUM (prevents fields silently missing from submission and skipped validation) + - 1.9 [Use the values Prop to Keep a Form in Sync with Server Data](references/formcfg-values-prop.md) — HIGH (replaces a useEffect+reset that overwrites edits whenever the query refetches) +2. [Field Subscription](references/_sections.md#2-field-subscription) — **CRITICAL** + - 2.1 [Avoid Calling watch() in Render for One-Time Reads](references/sub-avoid-watch-in-render.md) — HIGH (prevents unnecessary subscriptions and re-renders) + - 2.2 [React.memo Cannot Stop Context-Driven Re-renders Under FormProvider](references/sub-memo-cannot-beat-context.md) — MEDIUM (replaces a memo pass that has no effect with isolation that does) + - 2.3 [Use subscribe() to React to Form Changes Outside the React Lifecycle](references/sub-subscribe-outside-react.md) — HIGH (eliminates re-renders for non-UI consumers like analytics, autosave, telemetry) + - 2.4 [Use the Render-Prop Components to Isolate Re-renders Without a Child Component](references/sub-render-prop-components.md) — HIGH (confines a subscription to one subtree without authoring a wrapper component) + - 2.5 [Use useFormContext Sparingly for Deep Nesting](references/sub-useformcontext-sparingly.md) — MEDIUM (reduces prop drilling but increases implicit dependencies) + - 2.6 [Use useWatch Instead of watch for Isolated Re-renders](references/sub-usewatch-over-watch.md) — CRITICAL (confines value-change re-renders to the subscribing component) + - 2.7 [Watch Specific Fields Instead of Entire Form](references/sub-watch-specific-fields.md) — CRITICAL (reduces re-renders from N fields to 1 field change) +3. [Controlled Components](references/_sections.md#3-controlled-components) — **HIGH** + - 3.1 [Isolate Controlled Inputs in Dedicated Child Components](references/ctrl-usecontroller-isolation.md) — HIGH (re-renders only the changed field instead of the whole form) + - 3.2 [Wire Controller Field Props Correctly for UI Libraries](references/ctrl-controller-field-props.md) — HIGH (prevents a control that renders correctly but never writes back to the form) +4. [Validation Patterns](references/_sections.md#4-validation-patterns) — **HIGH** + - 4.1 [Build the Validation Schema Once, Outside the Render Path](references/valid-resolver-caching.md) — HIGH (stops rebuilding the whole schema object on every keystroke) + - 4.2 [Handle the NaN valueAsNumber Produces for an Empty Input](references/valid-valueasnumber-empty-nan.md) — HIGH (prevents an optional number field that can never be left blank) + - 4.3 [Surface Server Errors via setError('root.serverError', ...)](references/valid-server-errors.md) — HIGH (prevents lost server-side validation errors and unrecoverable form state) + - 4.4 [Use delayError to Debounce Rapid Error Display](references/valid-delay-error.md) — MEDIUM (reduces UI flicker during fast typing validation) +5. [State Management](references/_sections.md#5-state-management) — **MEDIUM-HIGH** + - 5.1 [Avoid isValid with onSubmit Mode for Button State](references/formstate-avoid-isvalid-with-onsubmit.md) — MEDIUM (prevents whole-form validation on every change under a deferred-validation mode) + - 5.2 [Read Every formState Property You Depend On During Render](references/formstate-destructure-formstate.md) — MEDIUM (prevents a component that never re-renders when the state it shows changes) + - 5.3 [Rebase Defaults with resetDefaultValues After a Successful Save](references/formstate-reset-default-values.md) — HIGH (clears isDirty without discarding edits made during the in-flight request) + - 5.4 [Use handleSubmit's Second Argument to Handle a Rejected Submit](references/formstate-handlesubmit-oninvalid.md) — MEDIUM (gives a failed submit somewhere to go instead of silently doing nothing) + - 5.5 [Use useFormState for Isolated State Subscriptions](references/formstate-useformstate-isolation.md) — MEDIUM (prevents parent re-renders from state access in children) + - 5.6 [Wrap Async Submit Handlers in try/catch and Reset on isSubmitSuccessful](references/formstate-async-submit-lifecycle.md) — HIGH (prevents stuck isSubmitting state and missing post-success reset) +6. [Field Arrays](references/_sections.md#6-field-arrays) — **MEDIUM-HIGH** + - 6.1 [Separate Sequential Field Array Operations](references/array-separate-crud-operations.md) — MEDIUM-HIGH (prevents state corruption from batched mutations) + - 6.2 [Use field.id as Key in useFieldArray Maps](references/array-use-field-id-as-key.md) — MEDIUM-HIGH (prevents state corruption and unnecessary re-renders) + - 6.3 [Use Single useFieldArray Instance Per Field Name](references/array-unique-fieldarray-per-name.md) — MEDIUM-HIGH (prevents state conflicts from duplicate subscriptions) + - 6.4 [useFieldArray's disabled Option Makes Every Mutation a Silent No-op](references/array-disabled-silently-noops.md) — MEDIUM-HIGH (prevents append/remove calls that vanish with no error or warning) +7. [Integration Patterns](references/_sections.md#7-integration-patterns) — **MEDIUM** + - 7.1 [Transform Values at Controller Level for Type Coercion](references/integ-value-transform.md) — MEDIUM (stops string input values reaching a number- or date-typed schema) + - 7.2 [Verify shadcn Form Component Import Source](references/integ-shadcn-form-import.md) — MEDIUM (prevents silent component mismatch bugs) + - 7.3 [Wire shadcn Select with onValueChange Instead of Spread](references/integ-shadcn-select-wiring.md) — MEDIUM (prevents a Radix Select that renders but never writes to the form) + +--- + +## References + +1. [https://react-hook-form.com/docs](https://react-hook-form.com/docs) +2. [https://react-hook-form.com/advanced-usage](https://react-hook-form.com/advanced-usage) +3. [https://react-hook-form.com/docs/useform](https://react-hook-form.com/docs/useform) +4. [https://react-hook-form.com/docs/useform/subscribe](https://react-hook-form.com/docs/useform/subscribe) +5. [https://react-hook-form.com/docs/useform/seterror](https://react-hook-form.com/docs/useform/seterror) +6. [https://react-hook-form.com/docs/useform/setvalue](https://react-hook-form.com/docs/useform/setvalue) +7. [https://react-hook-form.com/docs/useform/resetdefaultvalues](https://react-hook-form.com/docs/useform/resetdefaultvalues) +8. [https://react-hook-form.com/docs/useform/formstate](https://react-hook-form.com/docs/useform/formstate) +9. [https://react-hook-form.com/docs/usewatch](https://react-hook-form.com/docs/usewatch) +10. [https://react-hook-form.com/docs/usecontroller](https://react-hook-form.com/docs/usecontroller) +11. [https://react-hook-form.com/docs/usefieldarray](https://react-hook-form.com/docs/usefieldarray) +12. [https://react-hook-form.com/docs/useformstate](https://react-hook-form.com/docs/useformstate) +13. [https://github.com/react-hook-form/react-hook-form/releases](https://github.com/react-hook-form/react-hook-form/releases) +14. [https://github.com/react-hook-form/resolvers](https://github.com/react-hook-form/resolvers) +15. [https://ui.shadcn.com/docs/components/form](https://ui.shadcn.com/docs/components/form) + +--- + +## Source Files + +This document was compiled from individual reference files. For detailed editing or extension: + +| File | Description | +|------|-------------| +| [references/_sections.md](references/_sections.md) | Category definitions and impact ordering | +| [assets/templates/_template.md](assets/templates/_template.md) | Template for creating new rules | +| [SKILL.md](SKILL.md) | Quick reference entry point | +| [metadata.json](metadata.json) | Version and reference URLs | \ No newline at end of file diff --git a/.agents/skills/react-hook-form/README.md b/.agents/skills/react-hook-form/README.md new file mode 100644 index 0000000..be038dc --- /dev/null +++ b/.agents/skills/react-hook-form/README.md @@ -0,0 +1,126 @@ +# React Hook Form Best Practices Skill + +Corrective guidance for React Hook Form — the decisions that go wrong by default. + +## Overview + +This skill provides 35 rules across 7 categories. Every rule names a decision that a capable model gets wrong by default; rules that merely restated correct library behaviour were removed in 2.0.0. Verified against **react-hook-form 7.82.0** (July 2026), with every code block type-checked under `tsc --strict` against the real package types. + +### Directory Structure + +``` +react-hook-form/ +├── SKILL.md # Entry point with quick reference +├── AGENTS.md # Compiled comprehensive guide (TOC over references/) +├── metadata.json # Version, org, references +├── README.md # This file +├── assets/ +│ └── templates/ +│ └── _template.md # Rule template +└── references/ + ├── _sections.md # Category definitions and impact ordering + ├── formcfg-*.md # Form configuration rules (9) + ├── sub-*.md # Field subscription rules (7) + ├── ctrl-*.md # Controlled component rules (2) + ├── valid-*.md # Validation pattern rules (4) + ├── formstate-*.md # State management rules (6) + ├── array-*.md # Field array rules (4) + └── integ-*.md # Integration pattern rules (3) +``` + +## Validating + +This skill is validated by the repo-level tooling, not by per-skill scripts: + +```bash +npm run validate # structural validation of every skill +node /path/to/dev-skill/scripts/validate-skill.js . # discipline-aware validation of this skill +``` + +## Creating a New Rule + +1. Choose the appropriate category prefix: + +| Category | Prefix | Impact | +|----------|--------|--------| +| Form Configuration | `formcfg-` | CRITICAL | +| Field Subscription | `sub-` | CRITICAL | +| Controlled Components | `ctrl-` | HIGH | +| Validation Patterns | `valid-` | HIGH | +| State Management | `formstate-` | MEDIUM-HIGH | +| Field Arrays | `array-` | MEDIUM-HIGH | +| Integration Patterns | `integ-` | MEDIUM | + +2. Create a new file: `references/{prefix}-{slug}.md` + +3. Use the rule template from `assets/templates/_template.md` + +4. Add the rule to the SKILL.md quick reference and to the AGENTS.md table of contents (entries are ordered alphabetically by title within each section). + +## Rule File Structure + +```markdown +--- +title: Rule Title Here +impact: CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW +impactDescription: What the rule prevents or enables +tags: prefix, keyword1, keyword2 +--- + +## Rule Title Here + +Brief explanation of WHY this matters (1-3 sentences). + +**Incorrect (description of problem):** + +\`\`\`typescript +// Bad code with comment on key line +\`\`\` + +**Correct (description of solution):** + +\`\`\`typescript +// Good code with minimal diff from incorrect +\`\`\` + +Reference: [Documentation Link](https://example.com) +``` + +## File Naming Convention + +Rules follow the pattern: `{prefix}-{slug}.md` + +- **prefix**: Category identifier from `_sections.md` (lowercase letters only) +- **slug**: Kebab-case description of the rule + +Examples: +- `formcfg-validation-mode.md` +- `sub-usewatch-over-watch.md` +- `ctrl-usecontroller-isolation.md` + +## Impact Levels + +| Level | Description | +|-------|-------------| +| CRITICAL | Cascade effect on entire form performance | +| HIGH | Significant impact on specific operations | +| MEDIUM-HIGH | Notable improvement for common patterns | +| MEDIUM | Measurable improvement in specific scenarios | +| LOW-MEDIUM | Minor optimization for edge cases | +| LOW | Best practice with minimal performance impact | + +## Companion Skill + +`react-hook-form-audit` is a static-analysis skill that detects violations of these rules in a Next.js App Router codebase and links each finding back to the corresponding file in `references/`. + +## Contributing + +1. Read existing rules in the same category for style consistency +2. Ensure incorrect/correct examples have minimal diff +3. Typecheck every example against the pinned react-hook-form version before committing +4. Include authoritative reference links +5. Run validation before submitting + +## Acknowledgments + +Based on official React Hook Form documentation, the library's shipped type definitions, and community best practices. diff --git a/.agents/skills/react-hook-form/SKILL.md b/.agents/skills/react-hook-form/SKILL.md new file mode 100644 index 0000000..dcf50ed --- /dev/null +++ b/.agents/skills/react-hook-form/SKILL.md @@ -0,0 +1,113 @@ +--- +name: react-hook-form +description: React Hook Form performance optimization for client-side form validation using useForm, useWatch, useController, useFieldArray, the subscribe() API, and the Watch / FormStateSubscribe / FieldArray render-prop components. Covers RHF 7.82 additions including resetDefaultValues() and the disabled field-array option. This skill should be used when building client-side controlled forms with React Hook Form library. This skill does NOT cover React 19 Server Actions, useActionState, or server-side form handling (use react-19 skill for those). +--- + +# React Hook Form Best Practices by Community + +Comprehensive performance optimization guide for React Hook Form applications. Contains 35 rules across 7 categories, each naming a decision that goes wrong by default. Verified against react-hook-form **7.82.0**. + +## When to Apply + +Reference these guidelines when: +- Writing new forms with React Hook Form +- Configuring useForm options (mode, defaultValues, validation) +- Subscribing to form values with watch / useWatch / subscribe +- Integrating controlled UI components (MUI, shadcn, Ant Design) +- Managing dynamic field arrays with useFieldArray +- Handling async submit, server errors, and submit lifecycle state +- Reviewing forms for performance issues + +## When NOT to Use This Skill + +- **React 19 Server Actions / `useActionState`** — use the `react-19` skill instead +- **Deeply nested, fully type-safe forms** — TanStack Form may be a better fit for forms with complex nested schemas; this skill assumes you've already chosen RHF +- **Single-input or trivial forms** — uncontrolled `
` + `FormData` is often simpler than pulling in any library + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Form Configuration | CRITICAL | `formcfg-` | +| 2 | Field Subscription | CRITICAL | `sub-` | +| 3 | Controlled Components | HIGH | `ctrl-` | +| 4 | Validation Patterns | HIGH | `valid-` | +| 5 | State Management | MEDIUM-HIGH | `formstate-` | +| 6 | Field Arrays | MEDIUM-HIGH | `array-` | +| 7 | Integration Patterns | MEDIUM | `integ-` | + +## Quick Reference + +### 1. Form Configuration (CRITICAL) + +- `formcfg-default-values` - Always Provide defaultValues for Form Initialization +- `formcfg-useeffect-dependency` - Depend on formState Slices, Not on formState Itself +- `formcfg-validation-mode` - Justify Any mode Other Than the Default onSubmit +- `formcfg-revalidate-mode` - Keep Default reValidateMode Unless Validation Is Expensive +- `formcfg-should-unregister` - Keep shouldUnregister Off Unless Hidden Fields Must Leave the Payload +- `formcfg-transformed-values-generic` - Pass the Third useForm Generic When the Resolver Transforms Values +- `formcfg-async-default-values` - Use Async defaultValues for Server Data +- `formcfg-disabled-prop` - Use the HTML disabled Attribute for Visual Disabling, Not register's disabled Option +- `formcfg-values-prop` - Use the values Prop to Keep a Form in Sync with Server Data + +### 2. Field Subscription (CRITICAL) + +- `sub-avoid-watch-in-render` - Avoid Calling watch() in Render for One-Time Reads +- `sub-memo-cannot-beat-context` - React.memo Cannot Stop Context-Driven Re-renders Under FormProvider +- `sub-subscribe-outside-react` - Use subscribe() to React to Form Changes Outside the React Lifecycle +- `sub-render-prop-components` - Use the Render-Prop Components to Isolate Re-renders Without a Child Component +- `sub-useformcontext-sparingly` - Use useFormContext Sparingly for Deep Nesting +- `sub-usewatch-over-watch` - Use useWatch Instead of watch for Isolated Re-renders +- `sub-watch-specific-fields` - Watch Specific Fields Instead of Entire Form + +### 3. Controlled Components (HIGH) + +- `ctrl-usecontroller-isolation` - Isolate Controlled Inputs in Dedicated Child Components +- `ctrl-controller-field-props` - Wire Controller Field Props Correctly for UI Libraries + +### 4. Validation Patterns (HIGH) + +- `valid-resolver-caching` - Build the Validation Schema Once, Outside the Render Path +- `valid-valueasnumber-empty-nan` - Handle the NaN valueAsNumber Produces for an Empty Input +- `valid-server-errors` - Surface Server Errors via setError('root.serverError', ...) +- `valid-delay-error` - Use delayError to Debounce Rapid Error Display + +### 5. State Management (MEDIUM-HIGH) + +- `formstate-avoid-isvalid-with-onsubmit` - Avoid isValid with onSubmit Mode for Button State +- `formstate-destructure-formstate` - Read Every formState Property You Depend On During Render +- `formstate-reset-default-values` - Rebase Defaults with resetDefaultValues After a Successful Save +- `formstate-handlesubmit-oninvalid` - Use handleSubmit's Second Argument to Handle a Rejected Submit +- `formstate-useformstate-isolation` - Use useFormState for Isolated State Subscriptions +- `formstate-async-submit-lifecycle` - Wrap Async Submit Handlers in try/catch and Reset on isSubmitSuccessful + +### 6. Field Arrays (MEDIUM-HIGH) + +- `array-separate-crud-operations` - Separate Sequential Field Array Operations +- `array-use-field-id-as-key` - Use field.id as Key in useFieldArray Maps +- `array-unique-fieldarray-per-name` - Use Single useFieldArray Instance Per Field Name +- `array-disabled-silently-noops` - useFieldArray's disabled Option Makes Every Mutation a Silent No-op + +### 7. Integration Patterns (MEDIUM) + +- `integ-value-transform` - Transform Values at Controller Level for Type Coercion +- `integ-shadcn-form-import` - Verify shadcn Form Component Import Source +- `integ-shadcn-select-wiring` - Wire shadcn Select with onValueChange Instead of Spread + +## How to Use + +Read individual reference files for detailed explanations and code examples: + +- [Section definitions](references/_sections.md) - Category structure and impact levels +- [Rule template](assets/templates/_template.md) - Template for adding new rules +- Reference files: `references/{prefix}-{slug}.md` + +## Related Skills + +- For schema validation with Zod resolver, see `zod` skill +- For React 19 server actions, see `react-19` skill +- For UI/UX form design, see `frontend-design` skill + +## Full Compiled Document + +For the complete guide with all rules expanded: `AGENTS.md` diff --git a/.agents/skills/react-hook-form/assets/templates/_template.md b/.agents/skills/react-hook-form/assets/templates/_template.md new file mode 100644 index 0000000..4d0a698 --- /dev/null +++ b/.agents/skills/react-hook-form/assets/templates/_template.md @@ -0,0 +1,26 @@ +--- +title: Rule Title Here +impact: MEDIUM +impactDescription: Optional description of impact (e.g., "20-50% improvement") +tags: prefix, tag1, tag2 +--- + +## Rule Title Here + +Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications. + +**Incorrect (description of what's wrong):** + +```typescript +// Bad code example here +const bad = example() +``` + +**Correct (description of what's right):** + +```typescript +// Good code example here +const good = example() +``` + +Reference: [Link to documentation or resource](https://example.com) diff --git a/.agents/skills/react-hook-form/references/_sections.md b/.agents/skills/react-hook-form/references/_sections.md new file mode 100644 index 0000000..0d9d723 --- /dev/null +++ b/.agents/skills/react-hook-form/references/_sections.md @@ -0,0 +1,41 @@ +# Sections + +This file defines all sections, their ordering, impact levels, and descriptions. +The section ID (in parentheses) is the filename prefix used to group rules. + +--- + +## 1. Form Configuration (formcfg) + +**Impact:** CRITICAL +**Description:** Initial useForm setup determines validation timing, re-render boundaries, and what ends up in the submitted payload. The wrong mode validates on every keystroke; the wrong disabled or shouldUnregister setting silently drops data. + +## 2. Field Subscription (sub) + +**Impact:** CRITICAL +**Description:** Where a subscription lives decides how much of the tree re-renders. Reading a value at the form root instead of in the leaf that displays it is the difference between re-rendering the whole form and re-rendering one field. + +## 3. Controlled Components (ctrl) + +**Impact:** HIGH +**Description:** Controller and useController isolate re-renders only when they sit in a child component. Wiring their field props to a third-party control also has to match that library's prop names, or the input renders but never writes back. + +## 4. Validation Patterns (valid) + +**Impact:** HIGH +**Description:** Where the schema is constructed, how server-side failures re-enter the form, and how error display is paced. Building a schema inside render pays the construction cost on every keystroke. + +## 5. State Management (formstate) + +**Impact:** MEDIUM-HIGH +**Description:** formState is a per-property Proxy, so a value you never read during render is a value you never re-render for. Submit lifecycle belongs here too: an async handler that throws without a catch strands isSubmitting forever. + +## 6. Field Arrays (array) + +**Impact:** MEDIUM-HIGH +**Description:** Dynamic field management requires stable keys and one owner per field name. Some options — notably disabled — fail silently rather than loudly. + +## 7. Integration Patterns (integ) + +**Impact:** MEDIUM +**Description:** Third-party UI library integration (shadcn/Radix, MUI) requires specific wiring, and native inputs need explicit type coercion before values reach a typed schema. diff --git a/.agents/skills/react-hook-form/references/array-disabled-silently-noops.md b/.agents/skills/react-hook-form/references/array-disabled-silently-noops.md new file mode 100644 index 0000000..179ff73 --- /dev/null +++ b/.agents/skills/react-hook-form/references/array-disabled-silently-noops.md @@ -0,0 +1,56 @@ +--- +title: useFieldArray's disabled Option Makes Every Mutation a Silent No-op +impact: MEDIUM-HIGH +impactDescription: prevents append/remove calls that vanish with no error or warning +tags: array, useFieldArray, disabled, read-only, no-op +--- + +## useFieldArray's disabled Option Makes Every Mutation a Silent No-op + +`useFieldArray({ disabled })` (RHF 7.79+) is not a UI hint. When `disabled` is truthy, `append`, `prepend`, `insert`, `remove`, `swap`, `move`, `update`, and `replace` each return immediately — no mutation, no error, no console warning. Reaching for it as "grey the rows out while saving" produces a form where clicking Add does nothing and there is nothing in the console to explain why. + +**Incorrect (`disabled` tied to submit state — the append silently disappears):** + +```typescript +function TeamMembersFields({ control }: { control: Control }) { + const { isSubmitting } = useFormState({ control }) + const { fields, append, remove } = useFieldArray({ + control, + name: 'members', + disabled: isSubmitting, // Also kills append/remove, not just the visuals + }) + + return ( + <> + {fields.map((field, index) => ( + remove(index)} /> + ))} + + + ) +} +``` + +**Correct (disable the controls; reserve the option for genuinely read-only arrays):** + +```typescript +function TeamMembersFields({ control }: { control: Control }) { + const { isSubmitting } = useFormState({ control }) + const { fields, append, remove } = useFieldArray({ control, name: 'members' }) + + return ( + <> + {fields.map((field, index) => ( + remove(index)} disabled={isSubmitting} /> + ))} + + + ) +} +``` + +Use `disabled: true` when the array is structurally immutable for this user — a locked invoice, a plan the current role may not edit — where a mutation slipping through would be a bug. In that case `fields[index].disabled` (7.80+) carries the flag down to each row so the inputs can render disabled from the same source of truth. + +Reference: [useFieldArray](https://react-hook-form.com/docs/usefieldarray) diff --git a/.agents/skills/react-hook-form/references/array-separate-crud-operations.md b/.agents/skills/react-hook-form/references/array-separate-crud-operations.md new file mode 100644 index 0000000..9182fb2 --- /dev/null +++ b/.agents/skills/react-hook-form/references/array-separate-crud-operations.md @@ -0,0 +1,76 @@ +--- +title: Separate Sequential Field Array Operations +impact: MEDIUM-HIGH +impactDescription: prevents state corruption from batched mutations +tags: array, useFieldArray, append, remove, sequential +--- + +## Separate Sequential Field Array Operations + +Chaining `append()` and `remove()` in the same handler can cause state corruption. Defer removals to a useEffect or separate user action to allow React to process renders between operations. + +**Incorrect (stacked operations cause state issues):** + +```typescript +function ReplaceItemForm() { + const { control } = useForm() + const { fields, append, remove } = useFieldArray({ control, name: 'items' }) + + const replaceItem = (indexToReplace: number, newItem: Item) => { + remove(indexToReplace) // Remove old item + append(newItem) // Immediately add new - state may be stale + } + + return ( +
+ {fields.map((field, index) => ( + replaceItem(index, newItem)} + /> + ))} +
+ ) +} +``` + +**Correct (use update for replacements, or defer operations):** + +```typescript +function ReplaceItemForm() { + const { control } = useForm() + const { fields, update } = useFieldArray({ control, name: 'items' }) + + const replaceItem = (indexToReplace: number, newItem: Item) => { + update(indexToReplace, newItem) // Single atomic operation + } + + return ( +
+ {fields.map((field, index) => ( + replaceItem(index, newItem)} + /> + ))} +
+ ) +} +``` + +**Alternative (defer removal with useEffect):** + +```typescript +const [pendingRemoval, setPendingRemoval] = useState(null) + +useEffect(() => { + if (pendingRemoval !== null) { + remove(pendingRemoval) + setPendingRemoval(null) + } +}, [pendingRemoval, remove]) +``` + +Reference: [useFieldArray](https://react-hook-form.com/docs/usefieldarray) diff --git a/.agents/skills/react-hook-form/references/array-unique-fieldarray-per-name.md b/.agents/skills/react-hook-form/references/array-unique-fieldarray-per-name.md new file mode 100644 index 0000000..db00867 --- /dev/null +++ b/.agents/skills/react-hook-form/references/array-unique-fieldarray-per-name.md @@ -0,0 +1,58 @@ +--- +title: Use Single useFieldArray Instance Per Field Name +impact: MEDIUM-HIGH +impactDescription: prevents state conflicts from duplicate subscriptions +tags: array, useFieldArray, instance, state-management +--- + +## Use Single useFieldArray Instance Per Field Name + +Each field name should have only one useFieldArray instance. Multiple instances managing the same field name cause state conflicts and unpredictable behavior. + +**Incorrect (multiple instances for same field):** + +```typescript +function OrderForm() { + const { control } = useForm() + + return ( +
+ + +
+ ) +} + +function ItemsList({ control }: { control: Control }) { + const { fields, append } = useFieldArray({ control, name: 'items' }) // Instance 1 + return
{/* render items */}
+} + +function ItemsSummary({ control }: { control: Control }) { + const { fields } = useFieldArray({ control, name: 'items' }) // Instance 2 - conflicts! + return
Total items: {fields.length}
+} +``` + +**Correct (single instance, pass fields down or use useWatch):** + +```typescript +function OrderForm() { + const { control } = useForm() + const { fields, append, remove } = useFieldArray({ control, name: 'items' }) + + return ( +
+ + {/* Uses useWatch, not useFieldArray */} +
+ ) +} + +function ItemsSummary({ control }: { control: Control }) { + const items = useWatch({ control, name: 'items' }) // Read-only subscription + return
Total items: {items?.length ?? 0}
+} +``` + +Reference: [useFieldArray](https://react-hook-form.com/docs/usefieldarray) diff --git a/.agents/skills/react-hook-form/references/array-use-field-id-as-key.md b/.agents/skills/react-hook-form/references/array-use-field-id-as-key.md new file mode 100644 index 0000000..f9241df --- /dev/null +++ b/.agents/skills/react-hook-form/references/array-use-field-id-as-key.md @@ -0,0 +1,56 @@ +--- +title: Use field.id as Key in useFieldArray Maps +impact: MEDIUM-HIGH +impactDescription: prevents state corruption and unnecessary re-renders +tags: array, useFieldArray, key, react-key +--- + +## Use field.id as Key in useFieldArray Maps + +useFieldArray generates a unique `id` for each field. Using array index as key causes React to lose track of component identity when items are reordered, removed, or inserted. + +**Incorrect (index as key causes state corruption):** + +```typescript +function IngredientsForm() { + const { control, register } = useForm() + const { fields, append, remove } = useFieldArray({ control, name: 'ingredients' }) + + return ( +
+ {fields.map((field, index) => ( +
{/* Index key causes re-render issues */} + + +
+ ))} + +
+ ) +} +``` + +**Correct (field.id ensures stable identity):** + +```typescript +function IngredientsForm() { + const { control, register } = useForm() + const { fields, append, remove } = useFieldArray({ control, name: 'ingredients' }) + + return ( +
+ {fields.map((field, index) => ( +
{/* Stable identity across operations */} + + +
+ ))} + +
+ ) +} +``` + +**Forward compatibility:** `field.id` is correct for all of v7. The v8 beta line renames the generated render key to `field.key` and drops the `keyName` option, so `id` becomes an ordinary data property that no longer guarantees uniqueness. Do not pre-emptively switch on v7 — but if you set `keyName` to something custom today, that is the piece with no v8 equivalent. + +Reference: [useFieldArray](https://react-hook-form.com/docs/usefieldarray) diff --git a/.agents/skills/react-hook-form/references/ctrl-controller-field-props.md b/.agents/skills/react-hook-form/references/ctrl-controller-field-props.md new file mode 100644 index 0000000..5b5b349 --- /dev/null +++ b/.agents/skills/react-hook-form/references/ctrl-controller-field-props.md @@ -0,0 +1,56 @@ +--- +title: Wire Controller Field Props Correctly for UI Libraries +impact: HIGH +impactDescription: prevents a control that renders correctly but never writes back to the form +tags: ctrl, Controller, field-props, ui-libraries +--- + +## Wire Controller Field Props Correctly for UI Libraries + +Different UI libraries expect different prop names. Map Controller's field props correctly: `onChange` sends data back, `onBlur` reports interaction, `value` sets the display, `ref` enables focus on error. + +**Incorrect (spreading field on incompatible component):** + +```typescript +function FormWithSelect({ control }: { control: Control }) { + return ( + ( + + United States + United Kingdom + + )} + /> + ) +} +``` + +**Common mappings by library:** +- MUI Select: `value`, `onChange` (receives event) +- Radix/shadcn Select: `value`, `onValueChange` (receives value directly) +- React Select: `value`, `onChange` (receives option object) + +Reference: [useController](https://react-hook-form.com/docs/usecontroller) diff --git a/.agents/skills/react-hook-form/references/ctrl-usecontroller-isolation.md b/.agents/skills/react-hook-form/references/ctrl-usecontroller-isolation.md new file mode 100644 index 0000000..e5e7ae2 --- /dev/null +++ b/.agents/skills/react-hook-form/references/ctrl-usecontroller-isolation.md @@ -0,0 +1,80 @@ +--- +title: Isolate Controlled Inputs in Dedicated Child Components +impact: HIGH +impactDescription: re-renders only the changed field instead of the whole form +tags: ctrl, useController, Controller, controlled-components, re-renders +--- + +## Isolate Controlled Inputs in Dedicated Child Components + +`Controller` and `useController` are equivalent — `Controller` is a thin component wrapper around `useController`. Re-render isolation does **not** come from picking one over the other. It comes from putting the subscription in a **child component**, so that when the field value changes, only the child re-renders. Inlining `Controller` (or `useController`) in the parent form makes every parent re-render flow through every controlled input. + +**Incorrect (Controllers inlined in parent — every parent re-render re-renders all controlled inputs):** + +```typescript +function PaymentForm() { + const { control, handleSubmit } = useForm() + + return ( + + } + /> + } + /> + + ) +} +``` + +**Correct (subscription moved into dedicated child components, isolating re-renders to the changed field):** + +```typescript +function PaymentForm() { + const { control, handleSubmit } = useForm() + + return ( +
+ + + + ) +} + +function AmountInput({ control }: { control: Control }) { + const { field } = useController({ name: 'amount', control }) + return +} + +function CurrencySelectField({ control }: { control: Control }) { + const { field } = useController({ name: 'currency', control }) + return +} +``` + +**Equivalent with `Controller` (also correct — same isolation):** + +```typescript +function AmountField({ control }: { control: Control }) { + return ( + } + /> + ) +} +``` + +**When to prefer one API over the other:** +- `useController` — when you also need `fieldState`/`formState` in the same component, or want to compose with custom logic +- `Controller` — when you want a single JSX-only declaration and don't need to read state in the surrounding component + +Both achieve the same re-render isolation when placed in a child component. + +Reference: [useController](https://react-hook-form.com/docs/usecontroller) · [Controller](https://react-hook-form.com/docs/usecontroller/controller) diff --git a/.agents/skills/react-hook-form/references/formcfg-async-default-values.md b/.agents/skills/react-hook-form/references/formcfg-async-default-values.md new file mode 100644 index 0000000..edd42cd --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-async-default-values.md @@ -0,0 +1,69 @@ +--- +title: Use Async defaultValues for Server Data +impact: CRITICAL +impactDescription: eliminates manual useEffect reset patterns +tags: formcfg, async, default-values, data-fetching +--- + +## Use Async defaultValues for Server Data + +React Hook Form supports async functions for `defaultValues`, eliminating the need for manual useEffect + reset() patterns when loading initial data from an API. + +**Incorrect (manual useEffect reset pattern):** + +```typescript +function EditUserForm({ userId }: { userId: string }) { + const { register, reset, handleSubmit, formState: { isLoading } } = useForm({ + defaultValues: { + email: '', + name: '', + }, + }) + + useEffect(() => { + async function loadUser() { + const user = await fetchUser(userId) + reset(user) // Manual reset required + } + loadUser() + }, [userId, reset]) + + if (isLoading) return + + return ( +
+ + +
+ ) +} +``` + +**Correct (async defaultValues handles loading automatically):** + +```typescript +function EditUserForm({ userId }: { userId: string }) { + const { register, handleSubmit, formState: { isLoading } } = useForm({ + defaultValues: async () => { + const user = await fetchUser(userId) + return { + email: user.email, + name: user.name, + } + }, + }) + + if (isLoading) return + + return ( +
+ + +
+ ) +} +``` + +**Note:** defaultValues are cached after initial load. Use `reset()` with new values if you need to refresh data. + +Reference: [useForm - defaultValues](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formcfg-default-values.md b/.agents/skills/react-hook-form/references/formcfg-default-values.md new file mode 100644 index 0000000..7e6f5e4 --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-default-values.md @@ -0,0 +1,58 @@ +--- +title: Always Provide defaultValues for Form Initialization +impact: CRITICAL +impactDescription: prevents uncontrolled-to-controlled input warnings and a reset() with nothing to restore +tags: formcfg, default-values, initialization, useForm +--- + +## Always Provide defaultValues for Form Initialization + +`useForm()` with no `defaultValues` starts every field as `undefined`. Three things break at once: any controlled input flips from uncontrolled to controlled on first keystroke (React logs a warning and can lose the value), `reset()` with no arguments has no baseline to restore to, and `isDirty`/`dirtyFields` compare against nothing so the form reads as dirty the moment anything is touched. Provide the full shape up front, using empty strings rather than `undefined`. + +**Incorrect (no defaultValues — reset() has no baseline, inputs start uncontrolled):** + +```typescript +function ProfileForm({ user }: { user: User }) { + const { register, reset, handleSubmit } = useForm() + + useEffect(() => { + reset(user) + }, [user, reset]) + + return ( +
+ + + +
+ ) +} +``` + +**Correct (explicit defaults — reset() restores them, isDirty is meaningful):** + +```typescript +function ProfileForm({ user }: { user: User }) { + const { register, reset, handleSubmit } = useForm({ + defaultValues: { firstName: '', lastName: '' }, + }) + + useEffect(() => { + reset(user) + }, [user, reset]) + + return ( +
+ + + +
+ ) +} +``` + +When the defaults come from the server, pass them directly rather than defaulting-then-resetting — see `formcfg-async-default-values`. After a successful save, move the baseline with `resetDefaultValues` rather than `reset` (see `formstate-reset-default-values`). + +**Note:** Avoid custom objects with prototype methods (Moment, Luxon) as defaultValues — RHF deep-clones them. Use plain objects or primitives. + +Reference: [useForm - defaultValues](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formcfg-disabled-prop.md b/.agents/skills/react-hook-form/references/formcfg-disabled-prop.md new file mode 100644 index 0000000..606c34e --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-disabled-prop.md @@ -0,0 +1,83 @@ +--- +title: Use the HTML disabled Attribute for Visual Disabling, Not register's disabled Option +impact: MEDIUM +impactDescription: prevents fields silently missing from submission and skipped validation +tags: formcfg, register, disabled, validation, footgun +--- + +## Use the HTML disabled Attribute for Visual Disabling, Not register's disabled Option + +Passing `disabled: true` to `register` (or to `useController`/`Controller`) tells RHF the field is "not part of submission": `handleSubmit` deletes the field from the values object it hands your handler, and validation for that field is skipped. It is **not** the same as `` for purely visual disabling. If you only want the input greyed out, use the plain HTML attribute. + +The value itself is **not** destroyed — `handleSubmit` unsets disabled names from a *clone* of the form values, so `getValues('promoCode')` still returns what the user typed and re-enabling the field brings it back into the payload. The bug this causes is a field that quietly vanishes from your submit handler while the UI still shows a value in it. + +**Incorrect (using register's disabled option for visual disabling — promoCode silently disappears from the submitted payload):** + +```typescript +function CheckoutForm() { + const [usingGiftCard, setUsingGiftCard] = useState(false) + const { register, handleSubmit } = useForm({ + defaultValues: { promoCode: '', giftCardCode: '' }, + }) + + return ( +
+ + + +
+ ) +} +``` + +**Correct (use HTML disabled for visual-only disable; use register's disabled only when intentionally excluding the field):** + +```typescript +function CheckoutForm() { + const [usingGiftCard, setUsingGiftCard] = useState(false) + const { register, handleSubmit, watch } = useForm({ + defaultValues: { promoCode: '', giftCardCode: '', useShippingForBilling: true, billingAddress: '' }, + }) + const useShippingForBilling = watch('useShippingForBilling') + + return ( +
+ + + {/* Visual disable only: value stays in form state, validation still runs */} + + + + {/* Intentional exclusion: when checked, billingAddress is omitted from submission */} + + +
+ ) +} +``` + +**Rule of thumb:** +- Want the field greyed out but still submitted/validated → use the HTML `disabled` attribute directly on the input +- Want the field excluded from submission and validation → use `register('name', { disabled: true })` + +If a value is disappearing from your submit handler, check for this option before suspecting `getValues()` — the two disagree by design. + +Reference: [register - disabled](https://react-hook-form.com/docs/useform/register) diff --git a/.agents/skills/react-hook-form/references/formcfg-revalidate-mode.md b/.agents/skills/react-hook-form/references/formcfg-revalidate-mode.md new file mode 100644 index 0000000..9b917cb --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-revalidate-mode.md @@ -0,0 +1,58 @@ +--- +title: Keep Default reValidateMode Unless Validation Is Expensive +impact: MEDIUM +impactDescription: maintains immediate corrective feedback after first submit +tags: formcfg, revalidate-mode, validation, useForm +--- + +## Keep Default reValidateMode Unless Validation Is Expensive + +After the first submit, `reValidateMode` controls when fields re-validate. The default is `onChange`, which gives users immediate positive feedback the moment they fix an error — this is the recommended UX in most cases ("don't eagerly scold, but eagerly reward"). Only switch to `onBlur` or `onSubmit` when validation is genuinely expensive (async checks, large schemas, heavy regex on long inputs). + +**Incorrect (switching reValidateMode to onBlur for a cheap synchronous schema):** + +```typescript +function CheckoutForm() { + const { register, handleSubmit } = useForm({ + mode: 'onSubmit', + reValidateMode: 'onBlur', // Hurts UX: user fixes a wrong CVV and gets no feedback until blur + resolver: zodResolver(cheapSyncSchema), + }) + + return ( +
+ + +
+ ) +} +``` + +**Correct (default onChange revalidation; switch only when validation is genuinely expensive):** + +```typescript +function CheckoutForm() { + const { register, handleSubmit } = useForm({ + mode: 'onSubmit', + // reValidateMode: 'onChange' is the default — leave it for immediate feedback on correction. + // Switch to 'onBlur' only if you have an async check or >16ms-per-keystroke validation cost. + resolver: zodResolver(cheapSyncSchema), + }) + + return ( +
+ + +
+ ) +} +``` + +**When to deviate from the default:** +- Validation involves a network call or expensive computation (>16ms per keystroke) +- The form has dozens of fields and post-submit re-render cost is measurable in profiling +- The error message is purely informational, not correctable in real time + +Otherwise keep `onChange` — users who just fixed an error get instant validation success, which is the UX the RHF defaults are tuned for. + +Reference: [useForm - reValidateMode](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formcfg-should-unregister.md b/.agents/skills/react-hook-form/references/formcfg-should-unregister.md new file mode 100644 index 0000000..0ae5402 --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-should-unregister.md @@ -0,0 +1,56 @@ +--- +title: Keep shouldUnregister Off Unless Hidden Fields Must Leave the Payload +impact: HIGH +impactDescription: prevents silently dropping values the user already entered +tags: formcfg, should-unregister, dynamic-forms, conditional-fields +--- + +## Keep shouldUnregister Off Unless Hidden Fields Must Leave the Payload + +The default (`shouldUnregister: false`) keeps a field's value in form state after its input unmounts. That is the right default and it is not a memory problem — the retained data is a few strings per field. `shouldUnregister: true` is a **submission-shape** option: it removes unmounted fields from the values object entirely. Reaching for it to "clean up" a multi-step wizard silently deletes everything the user entered on step 1 the moment they advance to step 2. + +**Incorrect (wizard loses step 1 the moment step 2 renders):** + +```typescript +function OnboardingWizard() { + const [step, setStep] = useState(1) + const { register, handleSubmit } = useForm({ + shouldUnregister: true, // personalName is dropped as soon as step 1 unmounts + defaultValues: { personalName: '', companyName: '' }, + }) + + return ( +
+ {step === 1 && } + {step === 2 && } + +
+ ) +} +``` + +**Correct (default retention — every step survives to submit):** + +```typescript +function OnboardingWizard() { + const [step, setStep] = useState(1) + const { register, handleSubmit } = useForm({ + defaultValues: { personalName: '', companyName: '' }, + }) + + return ( +
+ {step === 1 && } + {step === 2 && } + +
+ ) +} +``` + +**When `shouldUnregister: true` is the right call:** +- A discriminated payload where the hidden branch's keys must be absent, not empty — e.g. a "Business" account sends `taxId` and a "Personal" one must not send the key at all +- A backend that treats a present-but-empty key differently from an absent one +- Set it per field via `register('taxId', { shouldUnregister: true })` rather than form-wide, so the rest of the form keeps the safe default + +Reference: [useForm - shouldUnregister](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formcfg-transformed-values-generic.md b/.agents/skills/react-hook-form/references/formcfg-transformed-values-generic.md new file mode 100644 index 0000000..a291b5b --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-transformed-values-generic.md @@ -0,0 +1,70 @@ +--- +title: Pass the Third useForm Generic When the Resolver Transforms Values +impact: CRITICAL +impactDescription: makes handleSubmit receive the schema's output type instead of its input type +tags: formcfg, generics, resolver, zod, transform, typescript +--- + +## Pass the Third useForm Generic When the Resolver Transforms Values + +`useForm` takes three generics: `useForm`. The first is what lives in the form (what inputs produce, before validation); the third is what `handleSubmit` hands your success callback. They are the same type only when the schema does no transformation. + +The moment a schema uses `z.coerce`, `.transform()`, or a `.default()`, input and output diverge — the form holds a string, the schema yields a `Date` or a `number`. Omit the third generic and TypeScript pins the output to the input type, which the resolver then contradicts. With `@hookform/resolvers` v5 the error lands on the `resolver:` property and reads like this: + +```text +Type 'Resolver<{ arrivesOn: string; … }, any, { arrivesOn: Date; … }>' is not assignable to +type 'Resolver<{ arrivesOn: string; … }, any, { arrivesOn: string; … }>'. + Types of property 'arrivesOn' are incompatible. + Type 'Date' is not assignable to type 'string'. +``` + +Nothing in that message mentions a missing generic, so the usual reactions are to cast the resolver, widen the schema until the transform is gone, or drop the resolver's type entirely — all of which trade a correct error for silently wrong types. This is the most common typing failure in RHF + Zod and the fix is one type argument. + +**Incorrect (one generic — the resolver's output type contradicts the form's, and handleSubmit is typed with the pre-validation input):** + +```typescript +const bookingSchema = z.object({ + guests: z.coerce.number().int().min(1), + arrivesOn: z.iso.date().transform((value) => new Date(value)), +}) + +type BookingInput = z.input + +function BookingForm() { + const { register, handleSubmit } = useForm({ + resolver: zodResolver(bookingSchema), + defaultValues: { guests: '1', arrivesOn: '' }, + }) + + // The resolver above fails to typecheck; values.arrivesOn is string, but is a Date at runtime + return
createBooking(values))} /> +} +``` + +**Correct (three generics — the callback is typed with the schema's output):** + +```typescript +const bookingSchema = z.object({ + guests: z.coerce.number().int().min(1), + arrivesOn: z.iso.date().transform((value) => new Date(value)), +}) + +type BookingInput = z.input +type BookingOutput = z.output + +function BookingForm() { + const { register, handleSubmit } = useForm({ + resolver: zodResolver(bookingSchema), + defaultValues: { guests: '1', arrivesOn: '' }, + }) + + // values.arrivesOn is Date, values.guests is number — matching runtime + return createBooking(values))} /> +} +``` + +The middle generic is the resolver context; pass `unknown` when you don't use one. Derive both types from the schema (`z.input` / `z.output`) rather than hand-writing them, so they can't drift. + +If `handleSubmit` is fighting you about a field type, check this generic before reaching for `as`. + +Reference: [useForm](https://react-hook-form.com/docs/useform) · [React Hook Form Resolvers](https://github.com/react-hook-form/resolvers) diff --git a/.agents/skills/react-hook-form/references/formcfg-useeffect-dependency.md b/.agents/skills/react-hook-form/references/formcfg-useeffect-dependency.md new file mode 100644 index 0000000..408db3b --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-useeffect-dependency.md @@ -0,0 +1,62 @@ +--- +title: Depend on formState Slices, Not on formState Itself +impact: HIGH +impactDescription: prevents effects that re-run on every keystroke +tags: formcfg, useEffect, dependencies, formState +--- + +## Depend on formState Slices, Not on formState Itself + +The `useForm()` return object is **stable**. `useForm` keeps it in a `useRef` and returns the same object on every render, mutating `formState` onto it — so `useEffect(fn, [form])` runs once, and `register`, `reset`, `control`, `setValue` and friends are all safe dependencies. (Widely repeated advice says the form object is a fresh reference each render and loops; that is not true of any v7 release.) + +The `formState` **proxy** is the part that changes. It is rebuilt via `useMemo` keyed on the underlying state, so it gets a new identity on every form-state update — every keystroke, in `onChange` mode. Depending on it re-runs the effect that often. Depend on the specific boolean you care about. + +**Incorrect (effect re-runs on every form-state update, not just on success):** + +```typescript +function ContactForm({ onSaved }: { onSaved: () => void }) { + const { register, handleSubmit, reset, formState } = useForm({ + defaultValues: { email: '' }, + }) + + useEffect(() => { + if (formState.isSubmitSuccessful) { + reset() + onSaved() + } + }, [formState, reset, onSaved]) // New proxy identity on every keystroke + + return ( + + + + ) +} +``` + +**Correct (depend on the slice that actually gates the effect):** + +```typescript +function ContactForm({ onSaved }: { onSaved: () => void }) { + const { register, handleSubmit, reset, formState: { isSubmitSuccessful } } = useForm({ + defaultValues: { email: '' }, + }) + + useEffect(() => { + if (isSubmitSuccessful) { + reset() + onSaved() + } + }, [isSubmitSuccessful, reset, onSaved]) // Only flips once per successful submit + + return ( +
+ +
+ ) +} +``` + +Destructuring also matters for a second reason: reading `formState.isSubmitSuccessful` is what registers the Proxy subscription in the first place — see `formstate-destructure-formstate`. + +Reference: [useForm](https://react-hook-form.com/docs/useform) · [formState](https://react-hook-form.com/docs/useform/formstate) diff --git a/.agents/skills/react-hook-form/references/formcfg-validation-mode.md b/.agents/skills/react-hook-form/references/formcfg-validation-mode.md new file mode 100644 index 0000000..903711f --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-validation-mode.md @@ -0,0 +1,55 @@ +--- +title: Justify Any mode Other Than the Default onSubmit +impact: CRITICAL +impactDescription: prevents a full validation pass and re-render on every keystroke +tags: formcfg, validation-mode, re-renders, useForm +--- + +## Justify Any mode Other Than the Default onSubmit + +`mode` decides when RHF validates. The default is `'onSubmit'`, and you should have to argue your way off it: `'onChange'` runs the field's validation — the whole resolver schema, if you use one — and re-renders on every keystroke. It gets reached for reflexively because "validate as they type" sounds like better UX, when in practice it means showing someone an "invalid email" error while they are still on the third character. + +**Incorrect (onChange chosen by default — errors fire mid-word, every keystroke re-validates):** + +```typescript +function RegistrationForm() { + const { register, handleSubmit, formState: { errors } } = useForm({ + mode: 'onChange', + defaultValues: { email: '' }, + }) + + return ( +
+ + {errors.email && {errors.email.message}} +
+ ) +} +``` + +**Correct (leave the default; escalate only where it earns its keep):** + +```typescript +function RegistrationForm() { + const { register, handleSubmit, formState: { errors } } = useForm({ + defaultValues: { email: '' }, + }) + + return ( +
+ + {errors.email && {errors.email.message}} +
+ ) +} +``` + +`reValidateMode` already defaults to `'onChange'`, so a field that has *failed* validation does give immediate feedback as the user corrects it — which is what people usually think they need `mode: 'onChange'` for. + +**Modes worth the escalation:** +- `onTouched` — validate after the first blur, then on change. The usual right answer when submit-time errors feel too late. +- `onBlur` — validate on blur only; quieter than `onTouched` while correcting. +- `onChange` — password-strength meters, "username is available" checks, live-computed totals. Add a comment saying which. +- `all` — `onBlur` and `onChange` together; rarely justified. + +Reference: [useForm - mode](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formcfg-values-prop.md b/.agents/skills/react-hook-form/references/formcfg-values-prop.md new file mode 100644 index 0000000..4f055ec --- /dev/null +++ b/.agents/skills/react-hook-form/references/formcfg-values-prop.md @@ -0,0 +1,61 @@ +--- +title: Use the values Prop to Keep a Form in Sync with Server Data +impact: HIGH +impactDescription: replaces a useEffect+reset that overwrites edits whenever the query refetches +tags: formcfg, values, resetOptions, react-query, server-state +--- + +## Use the values Prop to Keep a Form in Sync with Server Data + +When the initial data arrives from a query, the reflex is `useEffect(() => reset(data), [data])`. That works until the query refetches — on window focus, on interval, after an unrelated mutation — and the effect fires again mid-edit, wiping whatever the user had typed. + +`useForm({ values })` is the built-in answer. RHF re-syncs the form when the `values` reference changes, and `resetOptions: { keepDirtyValues: true }` tells it to leave fields the user has touched alone while updating the ones they haven't. `defaultValues` still supplies the shape before the first response lands. + +**Incorrect (effect-driven reset — a background refetch discards in-progress edits):** + +```typescript +function ProfileForm({ userId }: { userId: string }) { + const { data: profile } = useQuery({ queryKey: ['profile', userId], queryFn: fetchProfile }) + const { register, reset, handleSubmit } = useForm({ + defaultValues: { displayName: '', bio: '' }, + }) + + useEffect(() => { + if (profile) reset(profile) // Fires again on every refetch, mid-edit + }, [profile, reset]) + + return ( +
+ +
+ ) +} +``` + +**Correct (declarative sync that preserves what the user has touched):** + +```typescript +function ProfileForm({ userId }: { userId: string }) { + const { data: profile } = useQuery({ queryKey: ['profile', userId], queryFn: fetchProfile }) + const { register, handleSubmit } = useForm({ + defaultValues: { displayName: '', bio: '' }, + values: profile, + resetOptions: { keepDirtyValues: true }, + }) + + return ( +
+ +
+ ) +} +``` + +**Which initialiser to reach for:** +- `defaultValues` — the shape and the baseline; required regardless (see `formcfg-default-values`) +- `values` — the record is fetched and may change while the form is open +- async `defaultValues` — the record is fetched once and will not change under the form (see `formcfg-async-default-values`) + +Drop `keepDirtyValues` only when a server change should win over the user's edit — a record another person may be editing concurrently, for instance. + +Reference: [useForm - values](https://react-hook-form.com/docs/useform) diff --git a/.agents/skills/react-hook-form/references/formstate-async-submit-lifecycle.md b/.agents/skills/react-hook-form/references/formstate-async-submit-lifecycle.md new file mode 100644 index 0000000..806656e --- /dev/null +++ b/.agents/skills/react-hook-form/references/formstate-async-submit-lifecycle.md @@ -0,0 +1,79 @@ +--- +title: Wrap Async Submit Handlers in try/catch and Reset on isSubmitSuccessful +impact: HIGH +impactDescription: prevents stuck isSubmitting state and missing post-success reset +tags: formstate, isSubmitting, isSubmitSuccessful, async, submit, reset +--- + +## Wrap Async Submit Handlers in try/catch and Reset on isSubmitSuccessful + +`isSubmitting` is the canonical way to disable the submit button while a request is in flight, but it has a well-known footgun: if your submit handler **throws**, `isSubmitting` stays `true` and the form becomes unrecoverable. Always `try/catch` inside the async handler. Pair this with `isSubmitSuccessful` + `useEffect(reset)` to clear the form after a successful submit (resetting inside the handler races with the success state transition). + +**Incorrect (throw leaves isSubmitting stuck; manual reset races):** + +```typescript +function CreatePostForm() { + const { register, handleSubmit, reset, formState: { isSubmitting } } = useForm() + + const onSubmit = async (data: PostFormData) => { + const res = await fetch('/api/posts', { method: 'POST', body: JSON.stringify(data) }) + if (!res.ok) throw new Error('Save failed') // isSubmitting will stay true forever + reset() // Races with the form's success state + } + + return ( +
+ +