Capítulo 57 de 80

Chapter 57: FocusManager

Core Idea

The singleton behind window-focus refetching — swap its event source with setEventListener (as React Native's guide does with AppState) or override the focus state directly with setFocused, bypassing the DOM entirely.

Key Concepts

  • setEventListener(callback): replaces the default visibilitychange-based detection entirely — receives a handleFocus function to call with the new state, and must return a cleanup function (the previous listener is torn down when a new one is set).
  • subscribe(callback): notified with the current visibility boolean on every focus-state change — returns an unsubscribe function.
  • setFocused(focused): force the focus state (true/false), or pass undefined to fall back to the default detection mechanism.
  • isFocused(): synchronously reads the current focus state.

Code Examples

focusManager.setFocused(true)      // force "focused"
focusManager.setFocused(undefined) // revert to default (visibilitychange) detection
  • What it demonstrates: manually overriding focus state, then reverting to automatic detection.

Key Takeaways

  1. setEventListener fully replaces the default handler — you own detection entirely once you call it.
  2. setFocused(undefined) is the way back to default behavior after a manual override, not setFocused(true).

Connects To

  • Window Focus Refetching: this manager's role in the refetch-on-focus guide.
  • React Native: the concrete AppState-based setFocused wiring.