react-hook-form

bởi supabase

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-form

React 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:

APISubscribesRe-rendersUse for
useWatch({ control, name })yesonly the calling componentreactive value reads, anywhere
useFormState({ control })yesonly the calling componentisDirty/errors/etc. outside the form owner
formState (destructured)yesthe useForm ownerform state in the owner component only
form.watch(name)yesthe entire form treeavoid — lint-flagged, see below
getValues()noneverevent handlers and onSubmit only
subscribe()callbacknoneside effects outside render

Two facts explain most form bugs:

  1. form.watch() and form.formState hoist their subscription to the useForm owner, no matter where they are called. A child calling form.watch('x') off a prop works only by re-rendering the entire tree on every keystroke and silently goes stale behind React.memo. A no-arg form.watch() re-renders the whole tree on every field change.
  2. formState is 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.isValid may never subscribe). Enforced by react-hook-form/destructuring-formstate (error).

Reading values, by location

  • In the useForm owner: destructure formState; use useWatch over form.watch (no-use-watch flags every watch, and useWatch scopes re-renders if extracted later).
  • In any child component or custom hook: pass control (not form) and use useWatch({ control, name }) / useFormState({ control }), or read via useFormContext() + 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 pass name to useWatch so you don't subscribe to every field.
  • watch(callback) is deprecated: use subscribe() for render-free listeners and return its cleanup from useEffect.
// ❌ 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, static defaultValues, and singleton FORM_ID at module level so references stay stable. Only build a schema in useMemo when validation rules genuinely depend on runtime data; feed server-driven defaults via values (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 with useId() and share it between <form> and its buttons.
  • FormItemLayout + <FormControl> auto-ID contract:
    • Never pass manual id props to <FormItemLayout> or its child input — FormItem/FormLabel/FormControl auto-bind formItemId.
    • Wrap the single input control directly in <FormControl> (no layout <div> inside, which steals id and breaks label association). When a FormItemLayout renders multiple controls, give each additional control its own accessible label/aria-label.
    • Do not add redundant aria-label to controls already bound through <FormItemLayout> + <FormControl>.

defaultValues, server data, and reset

  • Provide complete defaultValues (every field, no undefined). isDirty, dirtyFields, and Cancel-reset all compare against it; missing or undefined defaults break all three and make React treat inputs as uncontrolled.
  • Server-populated forms: use values, not a useEffect. values reacts when the query resolves; computing defaultValues from an unloaded query freezes whatever was cached at mount. Add resetOptions: { keepDirtyValues: true } when background refetches must not clobber edits — note that resetOptions is inherited by every reset() call (including values updates, reset(response), and bare form.reset()), so any intentional reset that must replace or discard dirty edits (post-save or Cancel) must explicitly pass { keepDirtyValues: false }. For useFieldArray, destructure dirtyFields from form.formState in the owner (isDirty alone does not populate dirtyFields). (Example: components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx.)
  • Re-baseline after a successful mutation in onSuccess so isDirty clears and Cancel reverts to saved values. Disable edits while saving (Disabling and gating), then call form.reset(response, { keepDirtyValues: false }) using persisted server data (falling back to submittedValues only when the server stores values verbatim — a bare reset() reverts to previous defaults). Don't rely on values query invalidation alone: if the server normalizes input back to the previously loaded value (e.g. " A " → "A"), RHF deep-compares values and skips the reset.
  • Cancel & modal hygiene: Cancel calls form.reset() — or form.reset(undefined, { keepDirtyValues: false }) when keepDirtyValues: true is configured (the explicit undefined 1st argument is required when passing options). Never stack multiple useEffects calling form.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 to false.
  • Normalize null at the form boundary (growthPercent ?? '' inbound, '' → null on submit). Never paper over a null default with a value-like placeholder — 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 isDirty and show Cancel only when dirty (destructured from form.formState in the owner, or via useFormState({ control }) elsewhere).
  • For forms in a Sheet or Dialog, wire dirty dismissal via useConfirmOnClose + DiscardChangesConfirmationDialog and call raw onClose on save (see studio-ui-patterns and apps/design-system/content/docs/ui-patterns/modality.mdx).
  • Read dirtyFields from the same subscription to show which fields changed instead of hand-comparing defaultValues.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 (never onClick={() => 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 via getValues()). Follow Studio mutation conventions: onSuccess → toast.success + re-baseline form.reset(...) (above), and pass isSubmitting || isPending to the submit button's loading prop. Studio mutation hooks already emit a default toast.error when onError is omitted — keep error handling in a single layer: omit onError to use the default toast, or pass a hook-level onError whenever the call site owns error handling itself (inline or via mutateAsync + catch, see studio-queries).
  • Keep default mode: 'onSubmit' unless you have a deliberate reason to validate earlier.

Lint rules in force (Studio)

RuleLevelMeaning
react-hook-form/destructuring-formstateerrordestructure formState, never hold the object
react-hook-form/no-access-controlerrordon't reach into control internals
react-hook-form/no-nested-object-setvalueerrorsetValue('a.b', v), not setValue('a', {b:v})
react-hook-form/no-use-watcherroruse useWatch, not watch

Thêm skills từ supabase

ask-the-docs
supabase
Trả lời các câu hỏi về ứng dụng tài liệu Supabase (apps/docs) bằng cách sử dụng kiến trúc được ghi chép, quy trình build và các ghi chú về mẫu đánh giá, đồng thời áp dụng thiết kế tính năng…
clickhouse-logs-queries
supabase
Write, review, and migrate Supabase logs queries against the ClickHouse-backed `logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task…
copywriting
supabase
Viết hoặc kiểm tra nội dung UI (nút bấm, nhãn, trạng thái trống, thông báo lỗi, chú giải công cụ, văn bản biểu mẫu) ở bất kỳ đâu trong monorepo. Tải nó trước khi phát hành hoặc xem xét bất kỳ…
dev-toolbar-review
supabase
Sử dụng khi xem xét các PR liên quan đến packages/dev-tools/, packages/common/posthog-client.ts,
docs-content
supabase
Viết, chỉnh sửa, sắp xếp và xem lại nội dung Supabase ở bất kỳ đâu trong apps/docs — hướng dẫn, bài giải thích, bài hướng dẫn, mục xử lý sự cố, tài liệu tham khảo, và…
e2e-studio-tests
supabase
Chạy các bài kiểm tra e2e trong ứng dụng Studio. Sử dụng khi được yêu cầu chạy kiểm tra e2e, chạy kiểm tra studio, kiểm tra playwright, hoặc kiểm tra tính năng.
pm-the-docs
supabase
Hỗ trợ ra quyết định Docs-PM cho quy trình biên soạn "Write the docs" — đưa ra các quyết định về đối tượng, giai đoạn và phạm vi xuyên suốt trong các giai đoạn Frame và Shape,…
review-the-docs
supabase
Xem lại các thay đổi tài liệu Supabase cục bộ trong ~/GitHub/supabase/supabase — hoặc một PR đang mở (phân loại, phân nhóm, xác minh) hoặc nhánh của bạn trước khi mở PR (cục bộ…