Capítulo 22 de 39

Chapter 22: setValues

Core Idea

setValues(value, options?) (7.74.0+) updates several fields in one batched re-render — either from a plain partial-values object, or a callback deriving the next values from the current ones.

Key Concepts

  • value: Partial<TFieldValues> object, or (currentValues) => nextValues callback.
  • Batches into a single re-render: unlike calling setValue several times in sequence.
  • Does not reset the form: doesn't touch defaultValues — use reset if you need to reinitialize the baseline.
  • options: same shouldValidate/shouldDirty/shouldTouch/delayError (7.82.0+, requires shouldValidate: true) knobs as setValue, applied across all updated fields.

Code Examples

setValues({ firstName: "Bill", lastName: "Luo" })

setValues((data) => ({ ...data, name: "test" })) // derive from current values

setValues(
  { firstName: "Bill", lastName: "Luo" },
  { shouldValidate: true, shouldDirty: true, shouldTouch: true }
)
  • What it demonstrates: object form, callback form, and validating/dirtying/touching every updated field in one call.

Anti-patterns

  • Calling setValue repeatedly instead of setValues when updating several fields together: causes multiple re-renders instead of one batched update.
  • Expecting setValues to reinitialize defaultValues: it only writes current values; use reset for that.

Key Takeaways

  1. setValues is setValue for multiple fields at once, batched into one re-render.
  2. The callback form is the way to derive next values from current ones without a stale-closure read.

Connects To

  • useform-setvalue: the single-field equivalent.
  • useform-reset: the tool for actually reinitializing defaultValues.