useWatch:
({ control?: Control, name?: string, defaultValue?: unknown, disabled?: boolean }) => object
Behaves similarly to the watch
API, however, this will isolate re-rendering at the custom hook level and potentially result in better performance for your application.
Props
Name | Type | Description |
---|---|---|
name | string | string[] | undefined | Name of the field. |
control | Object | control object provided by useForm . It's optional if you are using FormContext. |
defaultValue | unknown | default value for Note: the first render will always return |
disabled | boolean = false | Option to disable the subscription. |
exact | boolean = false | This prop will enable an exact match for input name subscriptions. |
Rules
The initial return value from
useWatch
will always return what's inside ofdefaultValue
ordefaultValues
fromuseForm
.The only different between
useWatch
andwatch
is at root (useForm
) level or the custom hook level update.useWatch
execution order matters, which means if you are update form value before the subscription is in place, then the value update will be ignored.setValue('test', 'data'); useWatch({ name: 'test' }); // ❌ subscription is happened after value update, no update received useWatch({ name: 'example' }); // ✅ input value update will be received and trigger re-render setValue('example', 'data');
useWatch
result is optimised for render phase instead ofuseEffect
's deps, to detect value update you may want to use an external custom hook for value comparison.
Examples
import React from "react";
import { useForm, useWatch } from "react-hook-form";
function Child({ control }) {
const firstName = useWatch({
control,
name: "firstName",
});
return <p>Watch: {firstName}</p>;
}
export default function App() {
const { register, control } = useForm({
firstName: "test"
});
return (
<form>
<input {...register("firstName")} />
<Child control={control} />
</form>
);
}
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.