Capítulo 46 de 57

Chapter 46: Router Events

Core Idea

router.subscribe lets you observe the navigation lifecycle imperatively (analytics, DOM-dependent logic, external state cleanup) without driving rendering, by listening to a sequence of named events fired during navigation.

Key Concepts

  • router.subscribe: The subscription API for imperative side effects tied to navigation lifecycle events, distinct from reactive hooks used for rendering.
  • Event sequence: Navigation moves through onBeforeNavigateonBeforeLoadonLoadonBeforeRouteMountonResolvedonRendered.
  • onResolved: Fires after navigation completes; recommended event for analytics tracking.
  • onRendered: Fires after the DOM has been updated; recommended when logic depends on DOM content already being present.
  • Event payload: Each event includes location metadata such as fromLocation, toLocation, and boolean flags (pathChanged, hrefChanged, hashChanged).
  • Unsubscribing: Subscriptions return an unsubscribe function that should be called in cleanup (e.g. component unmount) to avoid memory leaks.
  • useRouterState: The recommended alternative when reactive UI updates (not just side effects) are needed, instead of manually subscribing.

Key Takeaways

  1. Use router.subscribe for side effects (analytics, logging, DOM manipulation), not for driving component rendering, that's what useRouterState and route hooks are for.
  2. Pick the narrowest event for the job: onResolved for analytics-style tracking, onRendered for DOM-dependent logic.
  3. Most use cases only need one or two of the six lifecycle events, not the entire sequence.
  4. Always clean up subscriptions by returning/calling the unsubscribe function to prevent leaks.

Connects To

  • Concept: useRouterState, the reactive counterpart for UI that needs to re-render on navigation state changes.
  • Ch 46 topic area: Analytics integrations and DOM-dependent third-party libraries commonly hook into onResolved/onRendered.