Skip to content

setValues

Update multiple field values at once.

</> setValues: (value: Partial<TFieldValues> | ((data: TFieldValues) => Partial<TFieldValues>), options?: SetValueConfig) => void

This function allows you to dynamically set multiple field values at once and have the options to validate and update the form state. It also accepts a callback function that receives the current form values, making it easy to derive the next state from the existing one.

Props


NameDescription
value
Partial<TFieldValues> | (data: TFieldValues) => Partial<TFieldValues>
An object containing the field values to update, or a callback function that receives the current form values and returns the updated values. This argument is required.
optionsshouldValidate
boolean
  • 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).
shouldDirty
boolean
  • 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).
shouldTouch
boolean
Whether to set the updated inputs to be touched.
RULES
  • When using the callback form, the function receives a snapshot of the current form values and should return only the fields you want to update.

  • This method does not reset the form. Use reset if you need to reinitialize defaultValues.

Examples


Basic

import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
firstName: "",
lastName: "",
},
})
return (
<form>
<input {...register("firstName")} />
<input {...register("lastName")} />
<button
type="button"
onClick={() => setValues({ firstName: "Bill", lastName: "Luo" })}
>
setValues
</button>
</form>
)
}

Callback (derive next state from current values)

import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
name: "",
count: 0,
},
})
return (
<form>
<input {...register("name")} />
<input type="number" {...register("count")} />
<button
type="button"
onClick={() => {
setValues((data) => {
return {
...data,
name: "test",
}
})
}}
>
setValues with callback
</button>
</form>
)
}

With options

import { useForm } from "react-hook-form"
const App = () => {
const { register, setValues } = useForm({
defaultValues: {
firstName: "",
lastName: "",
},
})
return (
<form>
<input {...register("firstName", { required: true })} />
<input {...register("lastName", { required: true })} />
<button
type="button"
onClick={() =>
setValues(
{ firstName: "Bill", lastName: "Luo" },
{ shouldValidate: true, shouldDirty: true, shouldTouch: true }
)
}
>
setValues with validation
</button>
</form>
)
}

Thank you for your support

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