Watching values
Subscribe to form value changes with onValuesChange, watch and useWatchValue
Package
Usage
useForm provides several ways to react to value changes. Pick the one that matches the task:
form.getValues()– read the current values in an event handler, see Form valuesform.useWatchValue(path)– render a part of the form based on a field valueform.watch(path, callback)– run an effect when a field changesonValuesChangeoption – react to any change in the form, for example to save values to local storage
form.useWatchValue
form.useWatchValue returns the current value of a field and rerenders the component only when that field changes.
Use it to render a part of the form based on a value:
Do not read values with form.getValues() during render, it does not rerender the component when the value changes:
form.useWatchValue is a hook, it cannot be called conditionally or inside loops:
form.watch
form.watch runs a callback when a field changes.
The callback receives the new value, previous value, touched and dirty states:
form.watch is a hook, it cannot be called conditionally or inside loops:
form.watch with arrays
With array fields, the callback is called when any nested field changes or when a list handler is called:
Total: $11
form.watch cascade
A watcher of a parent path is called when a nested field changes.
The reverse is not true: form.setFieldValue on a parent path does not call watchers of nested fields.
Set cascadeUpdates: true to change that:
{
"person": {
"name": ""
},
"name": ""
}onValuesChange
The onValuesChange function is called with new and previous values every time form values change.
Use it instead of useEffect to subscribe to form value changes: