mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
159 lines
14 KiB
Markdown
159 lines
14 KiB
Markdown
---
|
|
name: react-hook-form
|
|
description: Correct React Hook Form usage across the monorepo — data flow, subscriptions,
|
|
reset, dirty state, number inputs, and controlled-input rules. Load before writing or
|
|
editing any form, field, watch/useWatch/formState/getValues/setValue/reset, or
|
|
submit/cancel footer; older files contain anti-patterns. For layout and components, see
|
|
studio-ui-patterns.
|
|
---
|
|
|
|
# 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:
|
|
|
|
| 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:
|
|
|
|
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`.
|
|
|
|
```tsx
|
|
// ❌ 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`.
|
|
|
|
```tsx
|
|
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](#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 `useEffect`s 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:
|
|
|
|
```tsx
|
|
// 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)
|
|
|
|
| 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` |
|