react-hook-form
Sử dụng React Hook Form đúng cách ở bất kỳ đâu trong monorepo — luồng dữ liệu, đăng ký, reset, trạng thái dirty, input số và quy tắc input có kiểm soát. Tải cái này…
npx skills add https://github.com/supabase/supabase --skill react-hook-formReact Hook Form
The existing codebase is not a safe reference: form.watch() off prop-drilled form objects, subscription-only watches, unguarded valueAsNumber, and ?? undefined controlled values are common in older code and all wrong. Follow this skill, not the neighboring file.
Policy — fix what you touch. New code must follow these rules. When modifying existing form code, upgrade the specific fields/hooks/components you touch (e.g. convert form.watch to useWatch). Leave untouched code alone, but mention anti-patterns you noticed. Never add new violations: react-hook-form/no-use-watch is an ESLint error in Studio CI.
Mental model: subscriptions decide who re-renders
RHF is uncontrolled at heart. Values live in refs; nothing re-renders unless a subscription says so. Every read API is a subscription decision:
| API | Subscribes | Re-renders | Use for |
|---|---|---|---|
useWatch({ control, name }) | yes | only the calling component | reactive value reads, anywhere |
useFormState({ control }) | yes | only the calling component | isDirty/errors/etc. outside the form owner |
formState (destructured) | yes | the useForm owner | form state in the owner component only |
form.watch(name) | yes | the entire form tree | avoid — lint-flagged, see below |
getValues() | no | never | event handlers and onSubmit only |
subscribe() | callback | none | side effects outside render |
Two facts explain most form bugs:
form.watch()andform.formStatehoist their subscription to theuseFormowner, no matter where they are called. A child callingform.watch('x')off a prop works only by re-rendering the entire tree on every keystroke and silently goes stale behindReact.memo. A no-argform.watch()re-renders the whole tree on every field change.formStateis a Proxy — reading a property arms the subscription. Destructure it (const { isDirty } = form.formState), never pass the object around or read it conditionally (a && formState.isValidmay never subscribe). Enforced byreact-hook-form/destructuring-formstate(error).
Reading values, by location
- In the
useFormowner: destructureformState; useuseWatchoverform.watch(no-use-watchflags everywatch, anduseWatchscopes re-renders if extracted later). - In any child component or custom hook: pass
control(notform) and useuseWatch({ control, name })/useFormState({ control }), or read viauseFormContext()+useWatch({ name })inside<Form {...form}>. - Consume the return value & use one read path per render: never call a watch only for its subscription and read via
getValues()— the two lists drift and disagree within a render. Always passnametouseWatchso you don't subscribe to every field. watch(callback)is deprecated: usesubscribe()for render-free listeners and return its cleanup fromuseEffect.
// ❌ subscriptions hoist to the form owner and read paths drift
function Fields({ form }: { form: UseFormReturn<FormValues> }) {
form.watch(['storageType', 'totalSize'])
const { errors } = form.formState
const size = form.getValues('totalSize')
}
// ✅ child subscribes for itself and consumes what it watches
function Fields({ control }: { control: Control<FormValues> }) {
const [storageType, totalSize] = useWatch({ control, name: ['storageType', 'totalSize'] })
const { errors } = useFormState({ control })
}
The canonical form
zod schema → z.infer type → useForm with zodResolver and complete defaultValues → <Form {...form}> → FormField → FormItemLayout → FormControl → primitive from 'ui'. For Card vs Sheet layout and demos, see studio-ui-patterns.
const FORM_ID = 'pool-config-form'
const FormSchema = z.object({
name: z.string().min(1, 'Name is required'),
maxConnections: z
.union([z.literal(''), z.coerce.number().gte(1, 'Must be at least 1')])
.refine((v) => v !== '', 'Max connections is required'),
})
type FormValues = z.infer<typeof FormSchema>
const defaultValues: FormValues = { name: '', maxConnections: '' }
// Inside the component
const form = useForm<FormValues>({ resolver: zodResolver(FormSchema), defaultValues })
<Form {...form}>
<form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItemLayout layout="horizontal" label="Name">
<FormControl>
<Input {...field} />
</FormControl>
</FormItemLayout>
)}
/>
</form>
</Form>
- Module-level statics: define the schema,
type, staticdefaultValues, and singletonFORM_IDat module level so references stay stable. Only build a schema inuseMemowhen validation rules genuinely depend on runtime data; feed server-driven defaults viavalues(next section). Put input validation in the Zod schema so every input path (typing, paste, drag-and-drop) shares one contract. - External submit buttons: use
form={FORM_ID}for singleton forms; if the form can mount multiple instances at once, mint a per-instance id withuseId()and share it between<form>and its buttons. FormItemLayout+<FormControl>auto-ID contract:- Never pass manual
idprops to<FormItemLayout>or its child input —FormItem/FormLabel/FormControlauto-bindformItemId. - Wrap the single input control directly in
<FormControl>(no layout<div>inside, which stealsidand breaks label association). When aFormItemLayoutrenders multiple controls, give each additional control its own accessible label/aria-label. - Do not add redundant
aria-labelto controls already bound through<FormItemLayout>+<FormControl>.
- Never pass manual
defaultValues, server data, and reset
- Provide complete
defaultValues(every field, noundefined).isDirty,dirtyFields, and Cancel-reset all compare against it; missing orundefineddefaults break all three and make React treat inputs as uncontrolled. - Server-populated forms: use
values, not auseEffect.valuesreacts when the query resolves; computingdefaultValuesfrom an unloaded query freezes whatever was cached at mount. AddresetOptions: { keepDirtyValues: true }when background refetches must not clobber edits — note thatresetOptionsis inherited by everyreset()call (includingvaluesupdates,reset(response), and bareform.reset()), so any intentional reset that must replace or discard dirty edits (post-save or Cancel) must explicitly pass{ keepDirtyValues: false }. ForuseFieldArray, destructuredirtyFieldsfromform.formStatein the owner (isDirtyalone does not populatedirtyFields). (Example:components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx.) - Re-baseline after a successful mutation in
onSuccesssoisDirtyclears and Cancel reverts to saved values. Disable edits while saving (Disabling and gating), then callform.reset(response, { keepDirtyValues: false })using persisted server data (falling back tosubmittedValuesonly when the server stores values verbatim — a barereset()reverts to previous defaults). Don't rely onvaluesquery invalidation alone: if the server normalizes input back to the previously loaded value (e.g." A "→"A"), RHF deep-comparesvaluesand skips the reset. - Cancel & modal hygiene: Cancel calls
form.reset()— orform.reset(undefined, { keepDirtyValues: false })whenkeepDirtyValues: trueis configured (the explicitundefined1st argument is required when passing options). Never stack multipleuseEffects callingform.reset(), and reset form state cleanly when dialogs/sheets close or reopen so previous submissions don't leak.
Controlled inputs: never let value flip to undefined
React decides controlled vs uncontrolled per render from whether value is defined. Letting value become undefined (including on reset()) triggers console warnings and stops reset() from clearing DOM text. value={field.value ?? undefined} is a bug, not a fix.
- Default text fields to
'', selects/radios to''or a real option, and checkboxes/switches tofalse. - Normalize
nullat the form boundary (growthPercent ?? ''inbound,'' → nullon submit). Never paper over anulldefault with a value-likeplaceholder— it causes permanent phantom diffs and broken Cancel resets.
Number inputs
Keep '' as the empty sentinel so the input stays controlled and let zod coerce on validation (z.union([z.literal(''), z.coerce.number()...]).refine((v) => v !== '', '…') with <Input {...field} type="number" />).
Avoid register(name, { valueAsNumber: true }) (RHF converts '' to NaN internally and cannot be guarded inline) — use setValueAs on register, or guard e.target.valueAsNumber inside controlled field.onChange: field.onChange(Number.isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber).
For nullable API fields (null = unset), keep '' inside the form and convert at the boundaries:
// inbound: null → '' when building defaults/values
values: { growthPercent: data.growth_percent ?? '' },
// schema: '' stays the in-form sentinel, zod coerces real input
growthPercent: z.union([z.literal(''), z.coerce.number().gte(10).lte(100)]),
// outbound: '' → null in onSubmit
mutate({ growth_percent: values.growthPercent === '' ? null : values.growthPercent })
If legacy form state holds null, render via value={field.value ?? ''} and never pass it through z.coerce.number() (Number(null) silently validates as 0). Use one consistent sentinel per field across defaults, schema, onChange, rendering, and submit.
Dirty state and change detection
- Gate Save on
isDirtyand show Cancel only when dirty (destructured fromform.formStatein the owner, or viauseFormState({ control })elsewhere). - For forms in a Sheet or Dialog, wire dirty dismissal via
useConfirmOnClose+DiscardChangesConfirmationDialogand call rawonCloseon save (seestudio-ui-patternsandapps/design-system/content/docs/ui-patterns/modality.mdx). - Read
dirtyFieldsfrom the same subscription to show which fields changed instead of hand-comparingdefaultValues.x !== watchedX. - Pass explicit flags to programmatic
setValue:setValue('x', v, { shouldDirty: true, shouldValidate: true }).
Disabling and gating
When a field cannot be edited (plan tier, permissions via useAsyncCheckPermissions, cooldown) or while submitting/saving (isSaving = isSubmitting || isPending, covering both async validation and mutations), disable the control (and any related add/remove/cancel actions) with the same condition as the notice; use ButtonTooltip for disabled buttons needing explanation. Combine conditions on each control (disabled={!canEdit || isSaving}), or wrap native form controls in <fieldset disabled={isSaving}> (gating external footer buttons separately) so per-control disabled states stay intact.
Caution: register/useController disabled: true omits the field's value from submission data, so pass disabled to the input primitive (or readOnly on text inputs) whenever a locked value must survive submit. Avoid useForm({ disabled }) when any control relies on a primitive-only disabled prop — RHF writes ref.disabled = field._f.disabled || formDisabled onto registered refs (and sets field.disabled in FormField), so disabled: false can re-enable a permission-locked input.
Submit and mutations
- Use
type="submit"on submit buttons (neveronClick={() => onSubmit()}) so native submission and Enter-key behavior work, and ensure every validation failure surfaces a visible error. - Trust the validated, typed data passed to
onSubmit(don't re-read viagetValues()). Follow Studio mutation conventions:onSuccess→toast.success+ re-baselineform.reset(...)(above), and passisSubmitting || isPendingto the submit button'sloadingprop. Studio mutation hooks already emit a defaulttoast.errorwhenonErroris omitted — keep error handling in a single layer: omitonErrorto use the default toast, or pass a hook-levelonErrorwhenever the call site owns error handling itself (inline or viamutateAsync+catch, seestudio-queries). - Keep default
mode: 'onSubmit'unless you have a deliberate reason to validate earlier.
Lint rules in force (Studio)
| Rule | Level | Meaning |
|---|---|---|
react-hook-form/destructuring-formstate | error | destructure formState, never hold the object |
react-hook-form/no-access-control | error | don't reach into control internals |
react-hook-form/no-nested-object-setvalue | error | setValue('a.b', v), not setValue('a', {b:v}) |
react-hook-form/no-use-watch | error | use useWatch, not watch |