</> watch:
some overloads
This method will watch specified inputs and return their values. It is useful to render input value and for determining what to render by condition.
Overloads
This function mainly serves two purposes:
- Returns and keep sync with fields' values
a.
watch(name: string, defaultValue?): unknown
b.watch(names: string[], defaultValue?): {[key:string]: unknown}
c.watch(): {[key:string]: unknown}
- Start subscribing with given callback function (can be stopped by calling
unsubscribe
function) a.watch(callback: (data, { name, type }) => void, defaultValues?): { unsubscribe: () => void }
The explanation of each of these four overloads follows below.
1-a. Watching single field watch(name: string, defaultValue?: unknown): unknown
Watch and subscribe to a single field used outside of render.
Params
Name | Type | Description |
---|---|---|
name | string | the field name |
defaultValue | unknown | optional. default value for field |
Returns the single field value.
const name = watch("name")
1-b. Watching some fields watch(names: string[], defaultValue?: {[key:string]: unknown}): unknown[]
Watch and subscribe to an array of fields used outside of render.
Params
Name | Type | Description |
---|---|---|
names | string[] | the field names |
defaultValue | {[key:string]: unknown} | optional. default values for fields |
Returns an array of field values.
const [name, name1] = watch(["name", "name1"])
1-c. Watching the entire form watch(): {[key:string]: unknown}
Watch and subscribe to the entire form update/change based on onChange and re-render at the useForm.
Params None
Returns the entire form values.
const formValues = watch()
2. Start watching with callback fn watch(callback: (data, { name, type }) => void, defaultValues?: {[key:string]: unknown}): { unsubscribe: () => void }
Subscribe to field update/change without trigger re-render.
Params
Name | Type | Description |
---|---|---|
callback | (data, { name, type }) => void | callback function to subscribe to all fields changes |
defaultValues | {[key:string]: unknown} | optional. defaultValues for the entire form |
Returns object with unsubscribe
function.
useEffect(() => {const { unsubscribe } = watch((value) => {console.log(value)})return () => unsubscribe()}, [watch])
Rules
- When
defaultValue
is not defined, the first render ofwatch
will returnundefined
because it is called beforeregister
. It's recommended to providedefaultValues
atuseForm
to avoid this behaviour, but you can set the inlinedefaultValue
as the second argument. - When both
defaultValue
anddefaultValues
are supplied,defaultValue
will be returned. - This API will trigger re-render at the root of your app or form, consider using a callback or the useWatch api if you are experiencing performance issues.
watch
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:
Watch in a Form
import React from "react"import { useForm } from "react-hook-form"interface IFormInputs {name: stringshowAge: booleanage: number}function App() {const {register,watch,formState: { errors },handleSubmit,} = useForm<IFormInputs>()const watchShowAge = watch("showAge", false) // you can supply default value as second argumentconst watchAllFields = watch() // when pass nothing as argument, you are watching everythingconst watchFields = watch(["showAge", "age"]) // you can also target specific fields by their names// Callback version of watch. It's your responsibility to unsubscribe when done.React.useEffect(() => {const subscription = watch((value, { name, type }) =>console.log(value, name, type))return () => subscription.unsubscribe()}, [watch])const onSubmit = (data: IFormInputs) => console.log(data)return (<><form onSubmit={handleSubmit(onSubmit)}><input {...register("name", { required: true, maxLength: 50 })} /><input type="checkbox" {...register("showAge")} />{/* based on yes selection to display Age Input*/}{watchShowAge && (<input type="number" {...register("age", { min: 50 })} />)}<input type="submit" /></form></>)}
Watch in Field Array
import * as React from "react"import { useForm, useFieldArray } from "react-hook-form"type FormValues = {test: {firstName: stringlastName: string}[]}function App() {const { register, control, handleSubmit, watch } = useForm<FormValues>()const { fields, remove, append } = useFieldArray({name: "test",control,})const onSubmit = (data: FormValues) => console.log(data)console.log(watch("test"))return (<form onSubmit={handleSubmit(onSubmit)}>{fields.map((field, index) => {return (<div key={field.id}><inputdefaultValue={field.firstName}{...register(`test.${index}.firstName`)}/><inputdefaultValue={field.lastName}{...register(`test.${index}.lastName`)}/><button type="button" onClick={() => remove(index)}>Remove</button></div>)})}<buttontype="button"onClick={() =>append({firstName: "bill" + renderCount,lastName: "luo" + renderCount,})}>Append</button></form>)}
Video
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.