watch: (names?: string | string[] | (data, options) => void) => unknown
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.
Props
Type | Description | Example | Return |
---|---|---|---|
string | Watch input value by name (similar to lodash get function) | watch('inputName') watch('inputName', 'value') | any |
string[] | Watch multiple inputs | watch(['inputName1']) watch(['field1'], { field1: '1' }) | unknown[] |
undefined | Watch all inputs | watch() watch(undefined, { field: '1' }) | {[key:string]: unknown} |
(data: unknown, { name: string, type: string }) => void | Watch all inputs and invoke a callback | watch((data, { name, type }) => console.log(data, name, type)) | { unsubscribe: () => void } |
Rules
When
defaultValue
is not defined, the first render ofwatch
will returnundefined
because it is called beforeregister
. It's recommend 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
Video
The following video tutorial demonstrates watch
API.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.