Capítulo 12 de 39

Chapter 12: getFieldState

Core Idea

getFieldState(name, formState?) (7.25.0+) returns one field's { invalid, isDirty, isTouched, isValidating, error } — a type-safe way to read a single nested field's state instead of drilling into formState.errors/dirtyFields/touchedFields by hand.

Key Concepts

  • name must be a registered field: an unregistered name returns default/false state, not an error.
  • Subscription requirement: getFieldState reads from a formState subscription. If formState (or any of its properties) was already read/subscribed via useForm, useFormContext, or useFormState, the subscription already exists and the second argument is unnecessary. If no such subscription exists, pass the current formState object explicitly as the second argument, or getFieldState's result won't reflect live updates.

Code Examples

const { register, formState: { isDirty } } = useForm()
register("test")
getFieldState("test") // ✅ — formState.isDirty was read, so a subscription exists

// without any formState read:
const { register } = useForm()
register("test")
getFieldState("test") // ❌ not subscribed, may not reflect updates

const { register, formState } = useForm()
getFieldState("test", formState) // ✅ — pass formState explicitly instead
  • What it demonstrates: the subscription rule that decides whether the second argument is required.

Reference Tables

Return fieldRequires subscription to
isDirtydirtyFields
isTouchedtouchedFields
invaliderrors
isValidatingisValidating
errorerrors

Anti-patterns

  • Calling getFieldState without ever reading any formState property, and without passing formState explicitly: the returned state can be stale since nothing established the subscription.

Key Takeaways

  1. getFieldState needs a live formState subscription somewhere in the tree (via a read, or via the explicit second argument) to stay accurate.
  2. It's the type-safe route to a single field's combined dirty/touched/invalid/error/validating state.

Connects To

  • useform-formstate / useformstate: the subscription source getFieldState relies on.
  • usecontroller: fieldState there is the same shape, scoped to one controlled field automatically.