Capítulo 21 de 39
setValue(name, value, options?) dynamically updates a registered field's value while minimizing re-renders, with opt-in flags for whether the write should also trigger validation, mark dirty, or mark touched.
undefined.isValid), not the whole form's errors.isDirty always compares live values against defaultValues, a later unrelated update can still recompute dirtyFields and surface other fields that already differ from default — even ones previously written with shouldDirty: false.useForm({ delayError }); only applies when shouldValidate: true is also set.setValue("yourDetails.firstName", "value") is more performant than setValue("yourDetails", { firstName: "value" }); also, setValue on a dot-path only finds a field if that exact path was registered — updating a field that was registered with a nested object value (register("nestedValue", { value: {...} })) must target the same nested shape, not a sub-path.setValue can write directly into array entries (setValue("array.0.test1", "1")) without remounting, unlike useFieldArray's update/replace which do remount; for replacing an entire array, replace from useFieldArray is the purpose-built, preferred API — setValue on the whole array works today but may be discouraged later.setValue on a name nobody registered implicitly creates that field; for a nested shape, registering each leaf explicitly first lets a single setValue call on the parent update all of them correctly.setValue("firstName", "Bill")
setValue("firstName", "Luo", { shouldValidate: true, shouldDirty: true })
const [a, b] = watch(["a", "b"])
useEffect(() => {
if (formState.touchedFields.a && formState.touchedFields.b && a && b) {
setValue("c", `${a} ${b}`)
}
}, [setValue, a, b, formState])
setValue won't find the field; target the exact registered path instead.setValue to replace an entire field array instead of useFieldArray's replace: works today, but replace is the intended, more explicit tool and this usage may be discouraged later.shouldDirty: false permanently protects a field from ever showing as dirty: a later update elsewhere can still recompute and surface it as dirty via the isDirty/defaultValues comparison.setValue is the imperative write path — pair it with shouldValidate/shouldDirty/shouldTouch deliberately, since none of them are on by default.useFieldArray's replace/update over setValue.replace/update as the purpose-built alternative for array writes.delayError option this method's per-call flag opts into.