Forms that stay mounted
Switch records, validate against props, and submit with the latest callbacks.
Some forms outlive the props they were created with, like a detail pane that switches between customers or a transfer form whose parent passes a changing account balance or onSave callback.
useForm only reads its arguments on the first render. If props change on a later render (a different record, a new limit, or a fresh callback), the existing form instance keeps what it started with. Here is how to handle each case.
Switching between records
The simplest way to switch records is to give your form component a key tied to the record’s ID. When the key changes, React mounts a fresh component and initializes a new form with the new record’s values:
const customerForm = forms.define((saved: Customer) => ({
defaultValues: saved,
onSubmit: (value) => customers.save(value),
}));
function CustomerPane({ customer }: { readonly customer: Customer }) {
return <CustomerForm key={customer.id} saved={customer} />;
}
function CustomerForm({ saved }: { readonly saved: Customer }) {
const form = useForm(customerForm, saved);
// ...
}Unsaved edits from the previous record go away with the old form. If you’re receiving an updated copy of the same record (like a background refetch), keep the same key and rebase the form onto the fresh data so the user doesn’t lose what they’re typing.
Validating against live props
Because form definitions live outside your component, they can’t close over React props. Instead, attach prop-dependent rules inside the component with useValidator or the validate prop. Both always call the latest function from the current render:
function TransferForm({ balance }: { readonly balance: number }) {
const form = useForm(transferForm);
useValidator(form.root.at("amount"), (amount) =>
amount > balance ? { message: "That's more than the balance." } : undefined,
);
// ...
}Where you register the validator decides how long it stays active:
- On a field component (
form.Field’svalidateprop oruseValidatoron a field handle): active only while that field is mounted. Good for conditional UI, though a hidden wizard step won’t block submit. - On the form root (
useValidator(form.root, check)): active for the entire lifetime of the form.checkreceives the whole form value, so it can compare multiple fields against props at once. Its errors land on the root, so render root errors.
Note that a prop change by itself doesn’t re-run validation. If you want an error to update the moment balance changes, call validate() in an effect:
const amount = form.root.at("amount");
useEffect(() => {
void amount.validate();
}, [amount, balance]);Calling the latest prop callback on submit
When you use the function form of forms.define((input) => ...), useForm only passes input once on mount, so a callback passed directly through input would keep stale closures from that first render.
If the callback runs after a successful save (like closing a modal or showing a toast), you don’t need to pass it into the definition at all. Await form.submit() in your component’s submit handler, where you always have the latest props:
async function save(event: FormEvent) {
event.preventDefault();
const submission = await form.submit();
if (submission.status === "succeeded") onSaved(submission.result);
}
<form {...form.formProps} onSubmit={(event) => void save(event)}>If onSubmit itself needs a changing callback prop (such as a parent-provided onSave function), store the latest callback in a ref and pass a stable wrapper into useForm:
const customerForm = forms.define((input: { saved: Customer; save: (value: Customer) => Promise<void> }) => ({
defaultValues: input.saved,
onSubmit: (value) => input.save(value),
}));
function CustomerForm({ saved, onSave }: CustomerFormProps) {
const latest = useRef(onSave);
useEffect(() => {
latest.current = onSave;
});
const form = useForm(customerForm, { saved, save: (value) => latest.current(value) });
// ...
}Why a ref instead of React 19.2’s useEffectEvent? React only allows calling useEffectEvent functions from inside effects, whereas a form submit runs from an event handler. A ref works reliably everywhere.
Last updated