Capítulo 23 de 39

Chapter 23: subscribe

Core Idea

subscribe({ name?, formState?, callback, exact? }) (7.55.0+) reacts to form state/value changes with a plain callback, entirely outside React's render cycle — no component re-render involved.

Key Concepts

  • name: undefined (whole form), a single field name, or an array of names.
  • formState: pick which slices to subscribe to (values, isDirty, dirtyFields, touchedFields, isValid, errors, validatingFields, isValidating).
  • callback: receives the subscribed slice; runs without triggering a render.
  • exact: enable exact-match name subscriptions (same concept as useWatch/useFormState's exact).
  • Returns an unsubscribe function: call it (e.g. in a useEffect cleanup) to stop listening.
  • Shares mechanics with createFormControl's subscribe: the difference is createFormControl can be initialized outside a React component entirely.
  • Use this instead of watch's callback form when you specifically want to avoid any render — it's the dedicated no-render subscription API.

Code Examples

useEffect(() => {
  const unsubscribe = subscribe({
    formState: { values: true },
    callback: ({ values }) => console.log(values),
  })
  return () => unsubscribe()
}, [subscribe])
  • What it demonstrates: subscribing to value changes for side effects (analytics, non-React integrations) without causing the component to re-render.

Anti-patterns

  • Forgetting to call the returned unsubscribe function: leaks the subscription past the component's lifetime.
  • Using watch's callback overload where subscribe is the intended tool: subscribe is explicitly the no-render API; reach for it instead.

Key Takeaways

  1. subscribe is for side effects that must react to form changes without a render — analytics, logging, non-React integrations.
  2. Always clean it up (return the unsubscribe function from a useEffect).

Connects To

  • createformcontrol: shares the same subscribe mechanics, usable outside React entirely.
  • useform-watch / usewatch: the render-driven alternatives.