Replies: 1 comment
-
|
This is a known pain point with form-level validation — when the validator runs, it sets errors on every field it touches, and TanStack Form treats any error update as a state change that triggers a re-render, even if the error message is identical. A few strategies to mitigate this: 1. Use field-level validators instead of form-level If most of your validations are per-field, move them to <form.Field
name="startTime"
validators={{
onChange: ({ value }) => {
if (!value) return "Required"
if (!isValidTime(value)) return "Invalid time format"
return undefined
},
}}
>
{(field) => <TimeInput field={field} />}
</form.Field>For cross-field validations (where field A depends on field B), use <form.Field
name="endTime"
validators={{
onChangeListenTo: ["startTime"],
onChange: ({ value, fieldApi }) => {
const start = fieldApi.form.getFieldValue("startTime")
if (start && value && value <= start) return "Must be after start time"
return undefined
},
}}
>
{(field) => <TimeInput field={field} />}
</form.Field>2. Memoize your input components Wrap your field components in const TimeInput = React.memo(function TimeInput({ field }) {
return (
<input
value={field.state.value}
onChange={(e) => field.handleChange(e.target.value)}
/>
)
}, (prev, next) => {
return (
prev.field.state.value === next.field.state.value &&
JSON.stringify(prev.field.state.meta.errors) === JSON.stringify(next.field.state.meta.errors)
)
})3. Debounce form-level validation If you must use form-level validation, add an const form = useForm({
defaultValues: { /* ... */ },
validators: {
onChangeAsync: async ({ value }) => {
// your full-form validation
},
onChangeAsyncDebounceMs: 300,
},
})For 70+ fields, I'd strongly recommend approach #1 — move to field-level validators and use |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi!
I'm running into an issue where I have a form level validator that runs on change. This is our preferred way of validating as we have a few complex fields that interact with many others.
The problems comes when we have many fields that have errors. (the user has the ability to duplicate data and than later fix errors in each copy one by one). If a field changes the validator runs and validates the whole form, so far so good. But this causes all fields that got an error to re render even if the error it has did not actually change.
This can mean 70+ input componnes are re rendered when a singe input changes. This becomes even worse by the fact that our time input handles each keystroke as a change event.
Is there any way to:
Beta Was this translation helpful? Give feedback.
All reactions