Capítulo 25 de 39

Chapter 25: unregister

Core Idea

unregister(name, options?) removes a registered input's reference (and, by default, its built-in validation rules), with keepX flags to selectively preserve pieces of its state.

Key Concepts

  • Removes built-in validation, not schema validation: unregistering a field doesn't touch a resolver's schema — firstName stays required per a Yup/Zod schema even after unregister("firstName").
  • Namespace vs leaf: unregister("yourDetails") clears the whole nested object; unregister("yourDetails.firstName") clears just that leaf, leaving siblings.
  • keepDirty / keepTouched / keepIsValid / keepError / keepValue / keepDefaultValue / keepIsValidating: preserve that specific state slice instead of clearing it. keepDirty/keepIsValid don't guarantee the next user action won't recompute them anyway (both are measured live against defaultValues/schema). keepDefaultValue only matters when the form's top-level shouldUnregister is false (the default) — it's a no-op when shouldUnregister: true.
  • Must actually unmount the input too: calling unregister while the <input {...register(...)}> stays mounted just gets it re-registered — pair the call with removing/hiding the element.

Code Examples

unregister("yourDetails")               // {} — whole nested object gone
unregister("yourDetails.firstName")      // { lastName: '' } — one leaf gone
unregister(["yourDetails.lastName"])     // { firstName: '' } — array form
  • What it demonstrates: namespace-level vs. leaf-level unregistration.
const onClick = () => {
  unregister("test")
  setShow(false) // must also unmount, or register() re-adds it
}
{show && <input {...register("test")} />}
  • What it demonstrates: the required pairing of unregister with actually removing the input from the tree.

Anti-patterns

  • Calling unregister without unmounting the corresponding input: the input's own register call re-adds it on the next render.
  • Expecting unregister to remove a resolver/schema's validation rule for that field: it only clears RHF's internal reference/rules, not the schema itself.

Key Takeaways

  1. unregister and unmounting the input go together — neither alone fully removes a field.
  2. Schema-based validation is untouched by unregister; adjust the schema itself if needed.
  3. The keep* options are best-effort preservation, not permanent guarantees against later recomputation.

Connects To

  • useform-register: values/refs from register persist past unmount unless explicitly unregistered (or shouldUnregister is set).
  • useform: the global shouldUnregister option this method's keepDefaultValue interacts with.