Skip to content

setValue

Dynamically update a registered field's value.

</> setValue: UseFormSetValue

This function allows you to dynamically set the value of a registered field and provides options to validate and update the form state. At the same time, it attempts to avoid unnecessary re-renders.

Props


NameDescription
name
string
Target a single field or field array by name.
value
unknown
The value for the field. This argument is required and cannot be undefined.
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).
  • This option will update touchedFields at the specified field level, not the entire form's touched fields.
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).
  • This option will update dirtyFields at the specified field level, not the entire form's dirty fields.
shouldTouch
boolean
Since v7.8.0 Whether to set the input itself to be touched.
delayError
number
Since v7.82.0 Opt-in option that delays the display of the resulting validation error by the specified number of milliseconds. Only takes effect when shouldValidate is set to true.
RULES
  • shouldDirty only guarantees that the target field is marked in dirtyFields immediately. Because isDirty always compares current values against defaultValues, a later update to any field can trigger a dirtyFields recompute that also surfaces other fields whose value already differs from their default — including ones last written with shouldDirty: false.

  • You can use methods such as replace or update for a field array; however, they will cause the component to unmount and remount for the targeted field array.

    const { update } = useFieldArray({ name: "array" })
    // unmount fields and remount with updated value
    update(0, { test: "1", test1: "2" })
    // will directly update input value
    setValue("array.0.test1", "1")
    setValue("array.0.test2", "2")
  • It's recommended to target the field's name rather than make the second argument a nested object.

    setValue("yourDetails.firstName", "value") // ✅ performant
    setValue("yourDetails", { firstName: "value" })// less performant
    register("nestedValue", { value: { test: "data" } }) // register a nested value input
    setValue("nestedValue.test", "updatedData") // ❌ failed to find the relevant field
    setValue("nestedValue", { test: "updatedData" }) // ✅ setValue finds the input and updates it
  • It's recommended to register the input's name before invoking setValue. To update the entire FieldArray, make sure the useFieldArray hook is being executed first.

    Important: Use replace from useFieldArray instead; updating the entire field array with setValue will be removed in the next major version.

    // you can update an entire Field Array,
    setValue("fieldArray", [{ test: "1" }, { test: "2" }]) // ✅
    // you can use `setValue` on an unregistered input
    setValue("notRegisteredInput", "value") // ✅ prefer it to be registered
    // the following will register a single input (without register being invoked)
    setValue("resultSingleNestedField", { test: "1", test2: "2" }) // 🤔
    // With registered inputs, `setValue` will update both inputs correctly.
    register("notRegisteredInput.test", "1")
    register("notRegisteredInput.test2", "2")
    setValue("notRegisteredInput", { test: "1", test2: "2" }) // ✅ sugar syntax to setValue twice

Examples


Basic

import { useForm } from "react-hook-form"
const App = () => {
const { register, setValue } = useForm({
firstName: "",
})
return (
<form>
<input {...register("firstName", { required: true })} />
<button onClick={() => setValue("firstName", "Bill")}>setValue</button>
<button
onClick={() =>
setValue("firstName", "Luo", {
shouldValidate: true,
shouldDirty: true,
})
}
>
setValue options
</button>
</form>
)
}

Delay Error

setValue("firstName", "Bill", {
delayError: 500, // delay validation error updates by 500ms
shouldValidate: true,
})

Dependent Fields

import * as React from "react"
import { useForm } from "react-hook-form"
type FormValues = {
a: string
b: string
c: string
}
export default function App() {
const { watch, register, handleSubmit, setValue, formState } =
useForm<FormValues>({
defaultValues: {
a: "",
b: "",
c: "",
},
})
const onSubmit = (data: FormValues) => console.log(data)
const [a, b] = watch(["a", "b"])
React.useEffect(() => {
if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
setValue("c", `${a} ${b}`)
}
}, [setValue, a, b, formState])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("a")} placeholder="a" />
<input {...register("b")} placeholder="b" />
<input {...register("c")} placeholder="c" />
<input type="submit" />
<button
type="button"
onClick={() => {
setValue("a", "what", { shouldTouch: true })
setValue("b", "ever", { shouldTouch: true })
}}
>
trigger value
</button>
</form>
)
}

Video


Thank you for your support

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

Edit