Capítulo 61 de 80

Chapter 61: TimeoutManager

Core Idea

Every timer the library uses internally — staleTime/gcTime expiry, retries, throttling, debouncing — routes through timeoutManager, swappable via setTimeoutProvider for apps with thousands of concurrent queries hitting event-loop timer pressure, or needing delays past the browser's ~24-day setTimeout cap.

Key Concepts

  • Default behavior: uses the global setTimeout/setInterval — no configuration needed for typical apps.
  • setTimeoutProvider(provider): swaps in a custom TimeoutProvider (setTimeout/clearTimeout/setInterval/clearInterval implementations) — must be called before creating a QueryClient or any queries, since different providers can't cancel each other's timers, and consistency across the app depends on always using the same one.
  • When a custom provider is worth it: apps with thousands of queries may benefit from timer coalescing (batching similarly-timed callbacks, e.g. via a hierarchical time wheel data structure) rather than one raw timer per query — a custom TimeoutProvider is the extension point for that. It's also the way to exceed the ~24-day maximum delay of the platform's native setTimeout.
  • Timer ID typing: a TimeoutProvider's timer IDs can be a number or any object coercible to one via Symbol.toPrimitive — accommodates runtimes like Node.js, whose native setTimeout returns a Timeout object rather than a plain number.
  • Direct methods: setTimeout(callback, delayMs)/clearTimeout(id) and setInterval(callback, intervalMs)/clearInterval(id) — thin wrappers over whatever provider is currently configured, usable directly if code needs to schedule work through the same timer system the library itself uses.

Code Examples

// Must run before creating the QueryClient
timeoutManager.setTimeoutProvider(new CustomTimeoutProvider())
export const queryClient = new QueryClient()
  • What it demonstrates: the required ordering — provider set before any client/query creation.

Key Takeaways

  1. Set a custom TimeoutProvider before constructing QueryClient, never after — a mid-app provider switch can't reconcile timers already scheduled under the old one.
  2. This is a niche, high-scale optimization (thousands of concurrent queries) or a workaround for the native setTimeout delay cap — most apps never need it.

Connects To

  • persistQueryClient: the ~24-day gcTime/maxAge cap this manager's custom-provider escape hatch can work around.
  • Important Defaults: staleTime/gcTime, among the features implemented via this manager's timers.