useWatch: ({ control?: Control, name?: string, defaultValue?: any }) => object
Behaves similarly to the watch
API, however, this will isolate re-rendering at the component level and potentially result in better performance for your application.
Props
Name | Type | Description |
---|---|---|
name | string | string[] | Name of the field. |
control | Object | control object is from invoking useForm . it's optional if you are using FormContext. |
defaultValue | any | default value for useWatch to return before the initial render. |
import React from "react"; import { useForm, useWatch } from "react-hook-form"; function IsolateReRender({ control }) { const firstName = useWatch({ control, name: 'firstName', // without supply name will watch the entire form, or ['firstName', 'lastName'] to watch both defaultValue: 'default' // default value before the render }); return <div>{firstName}</div>; // only re-render at the component level, when firstName changes } function App() { const { register, control, handleSubmit } = useForm(); return ( <form onSubmit={handleSubmit(data => console.log("data", data))}> <input {...register("firstName")} /> <input {...register("last")} /> <IsolateReRender control={control} /> <input type="submit" /> </form> ); }
import React from "react"; import { useForm, useWatch } from "react-hook-form"; interface FormInputs { firstName: string } function FirstNameWatched({ control }: { control: Control<FormInputs> }) { const firstName = useWatch({ control, name: "firstName", // without supply name will watch the entire form, or ['firstName', 'lastName'] to watch both defaultValue: "default" // default value before the render }); return <p>Watch: {firstName}</p>; // only re-render at the component level, when firstName changes } function App() { const { register, control, handleSubmit } = useForm<FormInputs>(); const onSubmit = (data: FormInputs) => { console.log(data) }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label>First Name:</label> <input {...register("firstName")} /> <input type="submit" /> <FirstNameWatched control={control} /> </form> ); }
Tips
The initial return value from
useWatch
will always return what's inside ofdefaultValue
ordefaultValues
fromuseForm
.- The only different between
useWatch
andwatch is at root level or component level update.