| | |

Svelte Query 07 ⚡ Parallel & Paginated Queries — Orchestrating createQueries and smooth pagination with placeholderData

⏱️ Estimated read: 8 min | |

In real-world applications, data fetching is rarely a single, isolated event. Users expect dashboards that aggregate information from multiple sources simultaneously, and they expect lists that can be navigated without disruptive layout shifts or repeated loading spinners. TanStack Query provides a sophisticated API to manage these scenarios, moving beyond the basic single-query pattern into the realm of advanced data orchestration.

This chapter explores how to manage concurrent data requests using createQueries for parallel execution and how to create seamless list navigation using the placeholderData: keepPreviousData strategy. We will examine how these patterns prevent network waterfalls, improve perceived performance, and ensure that your UI remains interactive even when navigating through large datasets.

Key point: createQueries enables the concurrent execution of an arbitrary number of independent queries, while placeholderData: keepPreviousData prevents the UI from clearing during pagination transitions, keeping the “old” data visible until the “new” data arrives.


Why exists

The network waterfall problem. Without createQueries or careful orchestration, developers often define queries that fire sequentially. If a page needs five different resources, waiting for each to finish one after another adds unnecessary latency. Parallel orchestration allows all requests to fire simultaneously.

The pagination “flicker” problem. When a user clicks “Next Page,” the standard behavior is to reset the query, showing a loading spinner and an empty list. This is jarring. keepPreviousData provides a bridge, keeping the old results in the DOM until the new page has fully resolved, which creates a much smoother experience.

The dynamic count problem. In complex interfaces, the number of queries needed might depend on user selection. You cannot hardcode five createQuery calls if the user selects 10 items. createQueries allows you to dynamically define the number of concurrent queries based on runtime state.

The resource orchestration complexity. Managing state (loading, error, success) for multiple queries manually is a recipe for code bloat. TanStack Query abstracts this state management, providing a unified object that tracks the status of your parallel operations without requiring you to write complex Promise.all logic.

The consistency challenge. Ensuring that data remains synchronized across paginated fetches—especially if items appear or disappear—is notoriously difficult. The framework provides the structural guarantees needed to ensure that even when you are “keeping previous data,” the internal cache remains coherent with the server-side reality.


a. Parallel fetching with createQueries

The createQueries function is designed for fetching a dynamic list of data items. It accepts an array of query configuration objects and returns an array of query result objects. This is perfect for situations like a dashboard where you need to fetch specific details for several items whose IDs might change based on filters or user interactions.

// Fetching multiple user profiles in parallel
const userQueries = createQueries({
  queries: userIds.map((id) => ({
    queryKey: ['user', id],
    queryFn: () => fetchUser(id)
  }))
});

// Accessing the results
$: userResults = $userQueries.map(q => q.data);

Because createQueries is reactive, if the userIds array changes, the hook automatically updates, discarding queries that are no longer needed and initiating new ones. This eliminates the need to manually manage cleanup or state resets when your parallel fetching requirements change at runtime.


b. Seamless pagination with keepPreviousData

Pagination requires a stateful transition between pages. When using placeholderData: keepPreviousData, TanStack Query detects that the queryKey has changed (e.g., page 1 to page 2), but instead of resetting the data to undefined (which would hide your list), it keeps the data from page 1 visible until page 2 is fetched.

const query = createQuery({
  queryKey: ['posts', page],
  queryFn: () => fetchPosts(page),
  placeholderData: keepPreviousData
});

// UI remains populated during the transition
$: posts = $query.data ?? [];
$: isFetching = $query.isFetching;

This strategy is highly effective because it prevents the “Loading…” state from interrupting the user’s flow. You can use the isFetching flag to visually indicate that a background update is happening (e.g., dimming the list opacity), while the user continues to see the data they were just interacting with.


c. Advanced orchestration and composition

Combining these techniques requires a clear understanding of the query lifecycle. When you integrate createQueries with paginated components, you are essentially building a custom orchestration layer. You might use createQueries to fetch the metadata for a list of items and then use individual paginated queries to handle the details of those items as the user interacts with them.

// Advanced: Combining Parallel and Paginated
const listQuery = createQuery({
  queryKey: ['list'],
  queryFn: fetchIds
});

// Once we have IDs, we fetch details in parallel for the current page
$: detailQueries = createQueries({
  queries: ($listQuery.data || []).slice(start, end).map(id => ({
    queryKey: ['detail', id],
    queryFn: () => fetchDetail(id)
  }))
});

This approach allows you to build highly complex, interactive interfaces that feel snappy. The key is to keep the queryKey specific enough to track the resource, but generic enough to allow the cache to share results across different navigation states whenever possible.


Complete Example Session

// ============================================
// PART 1: DYNAMIC PARALLEL QUERY
// ============================================
const ids = [1, 2, 3];
const parallel = createQueries({
  queries: ids.map(id => ({
    queryKey: ['item', id],
    queryFn: () => fetchItem(id)
  }))
});

// ============================================
// PART 2: PAGINATION WITH KEEP-PREVIOUS
// ============================================
import { keepPreviousData } from '@tanstack/svelte-query';

const paginated = createQuery({
  queryKey: ['page', pageIndex],
  queryFn: () => fetchPage(pageIndex),
  placeholderData: keepPreviousData
});

// ============================================
// PART 3: UI INTEGRATION
// ============================================
{#if $paginated.isLoading}
  <p>Loading first page...</p>
{:else}
  <div class:dimmed={$paginated.isFetching}>
    {#each $paginated.data as item}
      <Item {item} />
    {/each}
  </div>
{/if}

// ============================================
// PART 4: DYNAMIC FILTERING PARALLEL
// ============================================
const filterQueries = createQueries({
  queries: filters.map(f => ({
    queryKey: ['filter', f],
    queryFn: () => fetchByFilter(f)
  }))
});

This sequence covers parallel execution, the transition logic for pagination, UI techniques for background fetching, and dynamic filtering.


Quick Reference

Orchestration Functions

FunctionUse Case
createQueriesFixed/Dynamic list of concurrent requests
keepPreviousDataSmooth UI transition during key changes
queryOptionsReusable query definition for parallel calls

State Flags

FlagMeaning
isFetchingTrue if background refetch is running
isLoadingTrue if first load is pending
isPlaceholderDataTrue if data is from a previous key

Best Practices

✅ Do This:

// Use keepPreviousData for paginated lists
placeholderData: keepPreviousData                          // ✅

// Map dynamic IDs to createQueries configuration
queries: ids.map(id => ({ ... }))                          // ✅

// Use isFetching to show non-blocking progress
class={ $query.isFetching ? 'dim' : '' }                   // ✅

// Combine with queryOptions for cleaner code
queries: ids.map(id => itemOptions(id))                    // ✅

❌ Don’t Do This:

// Don't manual-track parallel queries
const res1 = await fetch(1); const res2 = await fetch(2);  // ❌

// Don't ignore isPlaceholderData in UI
// It helps in styling the "stale" UI state                 // ❌

// Don't nest createQueries inside loops
// (It must be reactive-safe)                               // ❌

Common Pitfalls

PitfallWhy It HappensFix
UI jumpResetting state on paginated keysUse keepPreviousData
WaterfallDependent fetching in createQueriesUse enabled option
Over-fetchingcreateQueries key is too broadUse specific IDs in key
Memory bloatToo many concurrent queriesUse maxConcurrency (in config)

Real-World Examples

1. Dynamic Dashboard Widgets

const widgetQueries = createQueries({ queries: widgetList.map(w => ({ ... })) })

2. Paginated Table

queryKey: ['table', page], placeholderData: keepPreviousData

3. Search Suggestions (Parallel)

const searchQueries = createQueries({ queries: terms.map(t => ({ ... })) })

4. Background Dimming

opacity: $query.isFetching ? 0.5 : 1

5. Multi-Resource Load

const [user, posts] = createQueries({ queries: [userReq, postReq] })

6. Dynamic Filter Sync

const filtered = createQueries({ queries: selectedFilters.map(...) })

7. Avoiding Flash of Empty

placeholderData: keepPreviousData

8. Resource Detail Parallelism

createQueries({ queries: ids.map(id => detailOptions(id)) })

9. Query Client Prefetch

queryClient.prefetchQuery(nextPageOptions(page + 1))

10. Conditional Parallelism

queries: enabled ? ids.map(...) : []

Visual

Parallel Query Execution

┌──────────────────────────────────────────────┐
│  createQueries([Req A, Req B, Req C])        │
│    │                                         │
│    ├─► Req A ──────────┐                     │
│    ├─► Req B ───────┐  │ (All run together)  │
│    ├─► Req C ──────────┘                     │
│    │                                         │
│  Results arrive asynchronously               │
└──────────────────────────────────────────────┘

Paginated Smooth Transition

┌──────────────────────────────────────────────┐
│  Page 1 (Current Data)                       │
│    │                                         │
│  User clicks Next Page                       │
│    │                                         │
│  Page 2 (Fetching...)                        │
│    └─► Keep Page 1 visible until Page 2 hits │
│                                              │
│  Page 2 (Data arrived, swap)                 │
└──────────────────────────────────────────────┘

UI Feedback During Fetching

┌──────────────────────────────────────────────┐
│  State: isFetching = true                    │
│  [==========================-------]         │
│  Visual: Dim active list entries             │
│  Visual: Keep previous data in view          │
└──────────────────────────────────────────────┘

Summary

ItemValue
createQueriesParallel orchestration
keepPreviousDataSmooth pagination
isFetchingBackground progress check
placeholderDataState preservation during key change

Key takeaways:

  • Orchestrate parallelism with createQueries. Stop writing waterfalls; use the built-in hooks to fire requests simultaneously and manage their collective state.
  • Pagination must be seamless. Always use keepPreviousData when dealing with paginated content to prevent the “flicker” effect that destroys user confidence in the interface.
  • Understand the flags. isFetching is the key to creating “background update” animations, while isLoading remains reserved for the initial, blocking load.
  • Keep keys distinct. Even within createQueries, each request should have a unique key so the cache can effectively track and dedupe individual requests.
  • Component-level orchestration is powerful. Because Svelte Query is reactive, your createQueries map will re-run exactly when your array of IDs changes, making it the perfect tool for dynamic, data-driven interfaces.

Remember: Advanced data fetching isn’t just about loading data; it’s about the experience of the data loading. By mastering the concurrency of createQueries and the smoothness of keepPreviousData, you transform your application from a series of disjointed loads into a cohesive, fluid experience that feels significantly faster and more professional than a traditional request-response loop.

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!