Replies: 1 comment 2 replies
|
@OahMada The hook works, but there are two things worth knowing about it, one about performance and one about behaviour. 1. Where the re-renders happen
You can isolate that re-render by moving the hook into a tiny component that renders nothing: function ResetOn<T extends FieldValues>(props: {
control: Control<T>;
watch: FieldPath<T> | FieldPath<T>[];
reset: FieldPath<T>;
resetField: UseFormResetField<T>;
}) {
useResetField(props.control, props.watch, props.reset, props.resetField);
return null;
}
// inside the form
<ResetOn control={control} watch="field1" reset="field2" resetField={resetField} />Now only 2. The effect runs on mount and on programmatic changes, not only on user edits
3. If the rule is "user changed field1 → reset field2", you may not need a watcher at all
<input {...register('field1', { onChange: () => resetField('field2') })} />With I would keep the Small things: |
Uh oh!
There was an error while loading. Please reload this page.
Hi, this is a question regarding React Hook Form, I created an abstraction over RHF’s useWatch and the resetField method returned by useForm to streamline the process of resetting one field based on changes to one or more other fields, since this comes up quite often in the codebase I’m working on.
However, I’m not sure about the performance implications of this hook. What do you guys think?
All reactions