Skip to content

setValue

Update field value

setValue: (name: string, value: unknown, config?: Object) => void

This function allows you to dynamically set the value of a registered field and have the options to validate and update the form state. At the same time, it tries to avoid unnecessary rerender.

Props

NameTypeDescription
namestring
  • Target a single field by name.

  • When used with field array.

    • It's recommended to use field array's methods such as replace or update instead.

    • It will not create a new field when targeting a non-existing field.

valueunknown

The value for the field.

optionsshouldValidateboolean
  • Whether to compute if your input is valid or not (subscribed to errors).

  • Whether to compute if your entire form is valid or not (subscribed to isValid).

  • This option will update touchedFields at the specified field level not the entire form touched fields.
shouldDirtyboolean
  • Whether to compute if your input is dirty or not against your defaultValues (subscribed to dirtyFields).

  • Whether to compute if your entire form is dirty or not against your defaultValues (subscribed to isDirty).

  • This option will update dirtyFields at the specified field level not the entire form dirty fields.
shouldTouchboolean

Whether to set the input itself to be touched.

Rules

  • Only the following conditions will trigger a re-render:

    • When an error is triggered or corrected by a value update

    • When setValue cause state update, such as dirty and touched.

  • It's recommended to target the field's name rather than make the second argument a nested object.

  • It's recommended to register the input's name before invoking setValue. To update the entire Field Array, make sure the useFieldArray hook is being executed first.

    Important: use replace from useFieldArray instead, update entire field array with setValue will be removed in the next major version.

Examples

CodeSandbox

Video

The following video tutorial demonstrates setValue API in detail.

Thank you for your support

If you find React Hook Form to be useful in your project, please consider to star and support it.

Edit