Replies: 2 comments
|
This is supported now. It was released in 7.57.0. |
|
If you specifically want a React render when the brand value changes, import { useEffect, useRef } from 'react';
import { useForm, useWatch } from 'react-hook-form';
type Values = { carBrand: string; carModel: string };
function CarForm() {
const { register, control, resetField } = useForm<Values>({
defaultValues: { carBrand: '', carModel: '' },
});
const brand = useWatch({ control, name: 'carBrand', exact: true });
const previousBrand = useRef(brand);
useEffect(() => {
if (previousBrand.current === brand) return;
previousBrand.current = brand;
resetField('carModel', { defaultValue: '' });
}, [brand, resetField]);
return (
<form>
<input {...register('carBrand')} />
<input {...register('carModel')} />
</form>
);
}The previous-value guard avoids clearing a preloaded model on initial mount, including React Strict Mode's effect replay. This watches a string, not the entire form object. Model-only changes do not run the reset; Two details matter for this example:
I verified the effect pattern with React Hook Form 7.88.0 and React 19.2.4: initial edit values under Strict Mode, model-only edits, user/programmatic brand changes, repeated same-value updates, and the bulk-reset limitation above. References: useWatch, resetField. The documented |
Uh oh!
There was an error while loading. Please reload this page.
I found this unanswered question in another topic: #12946
The question is: how can we replace this functionality when we intentionally want to trigger a re-render based on field's change?
The new subscribe function does not support this directly.
I believe there are plenty of real-world scenarios where we want to react to a change in one field by updating another field. However, the current documentation does not suggest how we should properly migrate the deprecated watch callback fn.
Example:
What is the recommended way to achieve the same effect with the new API?
All reactions