Capítulo 20 de 39

Chapter 20: setFocus

Core Idea

setFocus(name, { shouldSelect? }) programmatically focuses a registered input by invoking the ref's focus() method.

Key Concepts

  • Requires a real registered ref: only works for inputs whose ref was actually attached during register — nothing to focus otherwise.
  • shouldSelect (7.27.0+): also selects the input's current content on focus.
  • Don't call right after reset(): reset removes all input references, so a setFocus call immediately after has nothing to focus.

Code Examples

useEffect(() => {
  setFocus("firstName")
}, [setFocus])
  • What it demonstrates: focusing a field on mount.

Anti-patterns

  • Calling setFocus immediately after reset(): the refs reset just cleared aren't there anymore.
  • Using it on a field with no attached ref (e.g. a controlled input via Controller whose target component doesn't forward refs): nothing happens.

Key Takeaways

  1. setFocus needs the field to be registered with a real DOM ref.
  2. Sequence matters: never call it right after reset().

Connects To

  • useform-register: the source of the ref setFocus uses.
  • useform-reset: sequencing hazard to be aware of.
  • useform: shouldFocusError is the automatic, validation-driven counterpart of manually calling setFocus.