| | |

Svelte Query 01 ⚡ Introduction & Server State — Separating client state from async data

⏱️ Estimated read: 7 min | |

Modern web applications are increasingly defined by their relationship with remote data. While Svelte excels at managing local, synchronous UI state through signals and runes, managing the asynchronous lifecycle of data fetched from a server introduces significant complexity. Developers often attempt to bridge this gap using standard lifecycle hooks like onMount, but this approach ignores the realities of network latency, caching, and state synchronization.

This chapter explores the fundamental distinction between client state and server state. We will examine why traditional fetch patterns create fragile, unscalable code and how Svelte Query (TanStack Query) provides a robust architecture to treat server data as a managed cache rather than an ephemeral side effect.

Key point: Server state is asynchronous, owned by a remote source, and requires mechanisms for caching, revalidation, and background updates; attempting to manage this with basic onMount and local state variables leads to unavoidable race conditions and stale data.


Why Svelte Query exists

Why exists

  • The Synchronization problem. Client state is synchronous and predictable; server state is inherently unreliable and changes without the client’s direct input.
  • The Loading/Error boilerplate problem. Managing loading, error, and data states manually for every single API call leads to massive amounts of repetitive, error-prone logic.
  • The Caching problem. Without a global cache, components often trigger identical network requests when re-mounted, resulting in redundant bandwidth usage and slower UI performance.
  • The Stale Data problem. Data fetched at a specific point in time becomes stale immediately, yet manual refetching mechanisms are difficult to coordinate across disjointed components.
  • The Background Update problem. Users expect an application to stay fresh, but refreshing the whole page or entire component trees is inefficient compared to updating specific data fragments in the background.

a. Client State vs. Server State

Client state is the UI-centric data owned by your application. This includes things like whether a modal is open, which tab is active, or the current value of an input field. In Svelte, we manage this efficiently using $state() runes or writable stores. This state is synchronous and controlled entirely by the user’s interactions within the browser.

Server state, conversely, is data that you do not own. It lives on a server, exists in a state of flux, and requires an asynchronous request to retrieve. Because the server is the “source of truth,” your local representation is merely a snapshot in time.

// Client state (Synchronous, Local)
let isModalOpen = $state(false);

// Server state (Asynchronous, Remote)
let userProfile = $state(null);
let isLoading = $state(false);

// We need an effect to sync the two
$effect(() => {
  fetch('/api/user').then(res => res.json()).then(data => userProfile = data);
});

When you treat server state like client state, you lose the ability to manage the lifecycle of that data. The code above is naive; it doesn’t handle revalidation if the user switches tabs, nor does it cache the profile for other components.

b. The Lifecycle Problem (onMount + fetch)

The common pattern of using onMount to initiate a fetch call is problematic for scaling. When a component is destroyed and re-mounted, the data is fetched again, even if the data hasn’t changed. This creates “flickering” UIs and unnecessary network traffic. Furthermore, if multiple components require the same data, each one will initiate its own request, leading to redundant work.

onMount(async () => {
  loading = true;
  const response = await fetch('/api/data');
  data = await response.json();
  loading = false;
});

This pattern forces the developer to manually manage every state transition. If a request fails, you must write custom error handling. If the data becomes stale, you have no built-in way to update it without triggering a full re-render of the component or manually calling the fetch function again from outside.

c. How Svelte Query solves the paradox

Svelte Query moves server state into a “Query Client,” which acts as an intelligent, asynchronous cache. Instead of “fetching,” you “subscribe” to a query. Svelte Query handles the loading states, error states, and background updates automatically.

import { useQuery } from '@tanstack/svelte-query';

const query = useQuery({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId)
});

// Access the managed state
$inspect(query.data);

By using a queryKey, Svelte Query tracks exactly what data is being fetched. If another component requests the same key, Svelte Query provides the cached version instantly while potentially refetching in the background to ensure freshness. It transforms server data from an ephemeral variable into a reactive, observable resource.


Complete Example Session

// ============================================
// PART 1: DEFINING THE QUERY
// ============================================
import { useQuery } from '@tanstack/svelte-query';

async function fetchPosts() {
  const res = await fetch('/api/posts');
  return res.json();
}

// ============================================
// PART 2: THE COMPONENT CONSUMPTION
// ============================================
const postsQuery = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts,
});

// ============================================
// PART 3: REACTIVE STATE ACCESS
// ============================================
let data = $derived(postsQuery.data);
let status = $derived(postsQuery.status);

// ============================================
// PART 4: HANDLING STATES
// ============================================
if (status === 'pending') { /* loading UI */ }
if (status === 'error') { /* error UI */ }

// ============================================
// PART 5: CACHE INVALIDATION
// ============================================
import { useQueryClient } from '@tanstack/svelte-query';
const client = useQueryClient();
client.invalidateQueries({ queryKey: ['posts'] });

This sequence demonstrates the shift from imperative fetch calls to declarative, cache-aware querying, ending with the ability to trigger invalidation to force fresh data.


Quick Reference

State Comparison

FeatureClient StateServer State
OwnershipLocalRemote
LatencyNone (Sync)High (Async)
Life CyclePage durationCache duration
SourceUser interactionNetwork request

Svelte Query Status

StatusMeaning
pendingNo data yet
successData successfully loaded
errorRequest failed

Benefits

BenefitDescription
CachingReuses fetched data
DedupingMerges duplicate requests
RevalidationRefreshes stale data
SSR SupportPre-fetches on server

Best Practices

✅ Do This:

// Define query keys consistently
queryKey: ['user', userId]                                    // ✅

// Always provide a queryFn
queryFn: () => fetchData(id)                                  // ✅

// Use derived state for clean access
let data = $derived(query.data)                               // ✅

// Invalidate queries after mutations
client.invalidateQueries({ queryKey: ['list'] })              // ✅

❌ Don’t Do This:

// Hardcode query keys directly in components
queryKey: ['user', 123]                                       // ❌

// Mix UI state with query logic
let data = $state(await fetch());                             // ❌

// Use onMount for initial data fetching
onMount(() => { ... })                                        // ❌

// Ignore status flags
return data.value;                                            // ❌

Common Pitfalls

PitfallWhy It HappensFix
Infinite LoopUpdating state in effectUse queryFn
Stale UICache not invalidatedinvalidateQueries
Flash of contentNo loading stateUse isPending
Race ConditionsFast typing/requestsUse queryKey versioning

Real-World Examples

1. Simple fetch

const q = useQuery({ queryKey: ['todo'], queryFn: fetchTodo });

2. Dependent query

const q = useQuery({ queryKey: ['posts', user.id], enabled: !!user.id });

3. Polling

useQuery({ queryKey: ['time'], queryFn: fetchTime, refetchInterval: 1000 });

4. Cache Time

useQuery({ ..., gcTime: 1000 * 60 * 5 });

5. Initial Data

useQuery({ ..., initialData: [] });

6. Mutation trigger

const mutation = useMutation({ mutationFn: savePost });

7. Query Client Access

const client = useQueryClient();

8. Prefetching

client.prefetchQuery({ queryKey: ['user'], queryFn: fetchUser });

9. Error Handling

if (query.isError) console.error(query.error);

10. Background refetching

useQuery({ ..., staleTime: 5000 });

Visual

The Cache Flow

┌──────────────────────────────────────────────┐
│  COMPONENT A        CACHE          SERVER    │
│  Request key ────► [ MISS ] ─────► Fetch     │
│                     [ DATA ] ◄───┘           │
│  Request key ────► [ HIT ]                   │
└──────────────────────────────────────────────┘

Lifecycle Comparison

┌──────────────────────────────────────────────┐
│  TRADITIONAL (onMount)                       │
│  Mount -> Fetch -> Done -> Destroy -> Gone   │
│                                              │
│  SVELTE QUERY                                │
│  Mount -> (Check Cache) -> (Fetch) -> Store  │
└──────────────────────────────────────────────┘

Reactive State Loop

┌──────────────────────────────────────────────┐
│  QUERY CLIENT                                │
│  ┌─────────────────────────┐                 │
│  │  State: Pending/Data    │◄─── Revalidate  │
│  └───────────┬─────────────┘                 │
│              │                               │
│        Subscribers (Runes)                   │
└──────────────────────────────────────────────┘

Summary

ItemValue
Primary goalManage server state
Core conceptQuery caching
Async logicDeclarative queryFn
State accessdata, isPending, error
StrategyCache-first, network-second

Key takeaways:

  • Server state is distinct. Unlike local UI state, it is remote, asynchronous, and inherently volatile.
  • onMount + fetch is inadequate. Manual fetching causes redundant requests and lacks caching capabilities.
  • Queries are declarative. You define what to fetch, and the library handles the when and how.
  • The Query Client is a cache. It tracks data across the application to ensure consistency and performance.
  • Invalidation is crucial. Manually invalidating queries ensures the UI stays in sync with the server after changes.

Remember: Svelte Query shifts the burden of async state management from the developer to an architecture designed specifically for the task. By treating network responses as cacheable resources rather than isolated events, you eliminate race conditions, redundant requests, and the complex boilerplate of loading/error state management.

Was this helpful?


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!