Svelte Query 02 ⚡ Setup & QueryClientProvider — Configuring QueryClient, global defaultOptions, and inspecting cache states with Svelte Query Devtools
Integrating Svelte Query into your project requires a top-level architectural decision: where to house the cache and how to propagate it through your component tree. Svelte Query uses a provider-based pattern, similar to how many state management libraries provide context to the UI. The core of this system is the QueryClient, which acts as the orchestrator for all asynchronous data fetching, caching, and state updates across your application.
This chapter covers the essential boilerplate required to initialize the library, starting with the creation of the QueryClient instance, its injection via the QueryClientProvider, and the usage of global defaults that dictate how your application handles data freshness. We will also examine how to leverage the Svelte Query Devtools to visualize your cache in real-time, allowing you to inspect the lifecycle of your server data as it moves through states like pending, fetching, or stale.
Key point: The QueryClient is the brain of Svelte Query; you must initialize it at the root of your application and wrap your components in the QueryClientProvider to ensure all children can access the cache, global defaults, and network lifecycle management.
Why exists
- The Global Cache access problem. Without a central client, individual components would have to instantiate their own storage, making it impossible to share data between disjointed UI trees.
- The Configuration overhead problem. Manually setting
staleTimeorretrylogic on every single query is repetitive and error-prone; global defaults centralize this logic. - The Dependency injection problem. Passing a client instance via props to deep components is cumbersome; the Provider pattern solves this by providing the client through the Svelte context API.
- The Observability problem. Developers need to know exactly what is in the cache to debug network issues; Devtools exist because raw state objects are difficult to traverse in the console.
- The Testability problem. By isolating the
QueryClient, you can easily replace the real network layer with a mock client for unit testing your components in isolation.
a. Initializing the QueryClient
The QueryClient is a class that manages the query cache and the configuration of your fetches. It is the object that keeps track of which keys are currently “fresh,” which are “stale,” and which are currently in flight. You should initialize this once at your application’s entry point—typically in your root layout or main entry file.
import { QueryClient } from '@tanstack/svelte-query';
// Central configuration for the app
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes
retry: 2,
},
},
});
By defining defaultOptions here, you enforce a consistent data-fetching strategy across the entire application. Whether you are fetching user details or product lists, these defaults ensure that your app behaves predictably regarding network retries and cache longevity.
b. Injecting the QueryClientProvider
Once the client is initialized, it must be provided to the component tree. The QueryClientProvider uses Svelte’s context API under the hood to inject the client so that any useQuery call inside its children can discover it without manual wiring.
<!-- +layout.svelte -->
<script>
import { QueryClientProvider } from '@tanstack/svelte-query';
import { queryClient } from './queryClient.js';
import { SvelteQueryDevtools } from '@tanstack/svelte-query-devtools';
let { children } = $props();
</script>
<QueryClientProvider client={queryClient}>
{@render children()}
<SvelteQueryDevtools />
</QueryClientProvider>
The placement is critical. By wrapping the root layout, you guarantee that every route and sub-component has access to the cache. Placing the SvelteQueryDevtools inside the provider allows it to tap into the same client instance to render a live, interactive map of your server state.
c. Debugging with Svelte Query Devtools
The SvelteQueryDevtools component is an essential debugging companion. It renders a floating panel that reveals the state of every query key, the time it was fetched, and its current status. It allows you to manually trigger refetches, reset queries, or expire the cache, which is invaluable during active development.
<!-- Devtools can be configured to start open or closed -->
<SvelteQueryDevtools initialIsOpen={false} />
Inside the Devtools, you can view the “Data Explorer,” which provides a JSON representation of your cached data. This eliminates the need to add console.log statements inside your queryFn to see what the server is returning. It exposes the transition between states (e.g., from pending to success) visually.
Complete Example Session
// ============================================
// PART 1: THE CONFIGURATION FILE
// ============================================
import { QueryClient } from '@tanstack/svelte-query';
export const queryClient = new QueryClient({
defaultOptions: {
queries: { gcTime: 1000 * 60 * 10 },
},
});
// ============================================
// PART 2: THE ROOT WRAPPER
// ============================================
// Svelte 5 syntax for layout components
<QueryClientProvider client={queryClient}>
<App />
<SvelteQueryDevtools />
</QueryClientProvider>
// ============================================
// PART 3: DEFINING A GLOBAL REFETCH ON FOCUS
// ============================================
const client = new QueryClient({
defaultOptions: {
queries: { refetchOnWindowFocus: true },
},
});
// ============================================
// PART 4: ACCESSING THE CLIENT
// ============================================
import { useQueryClient } from '@tanstack/svelte-query';
const client = useQueryClient(); // Used in any component
This sequence creates the client, provides it via context, sets global behavior, and shows how to pull that client instance into a leaf component for manual control.
Quick Reference
Default Options
| Option | Description |
|---|---|
staleTime | How long data is fresh |
gcTime | How long data stays in memory |
retry | Number of failed request retries |
refetchOnMount | Refetch when component mounts |
Provider Components
| Component | Role |
|---|---|
QueryClient | The brain/cache manager |
QueryClientProvider | Injects client into context |
SvelteQueryDevtools | Debug UI for the cache |
Global Behaviors
| Behavior | Logic |
|---|---|
refetchOnWindowFocus | Auto-refresh on focus |
retryDelay | Backoff logic for failures |
Best Practices
✅ Do This:
// Create the client in a dedicated file
export const client = new QueryClient(); // ✅
// Always set a reasonable staleTime
staleTime: 5000 // ✅
// Wrap your main root layout
<QueryClientProvider client={client}> // ✅
// Keep devtools in dev builds only
{import.meta.env.DEV && <SvelteQueryDevtools />} // ✅
❌ Don’t Do This:
// Initialize client inside a component
const client = new QueryClient(); // Re-inits on render! // ❌
// Rely on infinite staleTime
staleTime: Infinity // ❌
// Forget to add the Provider
// (useQuery will throw) // ❌
// Leave devtools in production
<SvelteQueryDevtools /> // (Bloats production code) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Client reset | Initializing inside +page.svelte | Init in external module |
| Missing Provider | Calling hooks outside tree | Wrap app in QueryClientProvider |
| Cache bloat | gcTime is too long | Configure reasonable gcTime |
| Devtools lag | Too many logs in Devtools | Filter by key in Devtools |
Real-World Examples
1. Customizing retries
retry: (failureCount) => failureCount < 3
2. Disabling window focus refetch
refetchOnWindowFocus: false
3. Setting cache duration
gcTime: 1000 * 60 * 60 // 1 hour
4. Initializing with defaults
new QueryClient({ defaultOptions: { queries: { retry: 1 } } })
5. Using the client instance
client.getQueryData(['user', 1])
6. Invalidate all
client.invalidateQueries({ queryKey: ['users'] })
7. Prefetching route data
client.prefetchQuery({ queryKey: ['list'], queryFn: fetchList })
8. Clearing cache
client.clear()
9. Setting custom logger
new QueryClient({ logger: customLogger })
10. Query client context hook
const client = useQueryClient();
Visual
The Provider Architecture
┌──────────────────────────────────────────────┐
│ ROOT LAYOUT │
│ ┌────────────────────────────────────────┐ │
│ │ QueryClientProvider (Holds Cache) │ │
│ │ ┌──────────┬───────────┬────────────┐ │ │
│ │ │ Route 1 │ Route 2 │ Devtools │ │ │
│ │ └──────────┴───────────┴────────────┘ │ │
│ └────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘
QueryClient Initialization
┌──────────────────────────────────────────────┐
│ queryClient.ts │
│ ┌────────────────────────────────────────┐ │
│ │ new QueryClient({ │ │
│ │ defaultOptions: { queries: { ... } }│ │
│ │ }) │ │
│ └────────────────────────────────────────┘ │
│ │ (Shared Exported Instance) │
└──────────────────────────────────────────────┘
Lifecycle State Inspection
┌──────────────────────────────────────────────┐
│ DEVTOOLS PANEL │
│ ┌────────────────────────────────────────┐ │
│ │ [ ACTIVE ] ['users', 1] │ │
│ │ [ STALE ] ['config'] │ │
│ │ [ FETCH ] ['notifications'] │ │
│ └────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Initialization | new QueryClient() |
| Injection | QueryClientProvider |
| Debugging | SvelteQueryDevtools |
| Defaults | defaultOptions |
| Context | Svelte Context API |
Key takeaways:
- The
QueryClientis the single source of truth. It should be instantiated outside the component lifecycle to prevent data loss on re-renders. - Provider is mandatory. Without
QueryClientProvider, theuseQueryhooks lack the necessary context to communicate with the cache. - Global defaults optimize UX. Setting
staleTimeandretrybehavior once at the top level keeps your code DRY and ensures consistency. - Devtools provide transparency. Use the visual debugger to track cache states, investigate timing issues, and manually manipulate your data layer during development.
- Testability. Centralized configuration makes it simple to swap the
QueryClientduring integration tests or when moving between different environments (e.g., mock vs. production).
Remember: Setting up Svelte Query correctly is about establishing a robust infrastructure for your data. By placing the QueryClient and QueryClientProvider at the root of your application, you create a shared state container that manages the complexities of network status, caching, and background synchronization, allowing your components to remain focused solely on rendering the UI.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!