Vue Query 07 ⚡ Parallel, Dependent & Paginated Queries — Orchestrating useQueries, dependent enabled chains, and placeholderData: keepPreviousData
Data fetching in complex applications is rarely a single, isolated event. Most screens require data from multiple endpoints, where one request might rely on the output of another, or where data arrives in chunks over time through pagination. Handling these scenarios manually often leads to “waterfall” requests (where the app waits for one request to finish before starting the next) or flickering UI states that degrade the user experience.
Vue Query provides a declarative toolkit to manage these complex orchestration patterns. Instead of managing state manually with ref or computed properties, you can define the relationships between your queries. Parallel queries can be bundled to avoid waterfalls, dependent queries can be orchestrated using the enabled option to create execution chains, and paginated lists can be smoothed out using placeholder data to prevent UI jumps.
This chapter covers the three core orchestration strategies in Vue Query. We will explore how useQueries enables true parallel fetching, how to build dependent query chains using reactive enabled flags, and how to master pagination UX with keepPreviousData. By the end of this guide, you will be able to synchronize multiple asynchronous data sources with minimal boilerplate.
Key point: Orchestration in Vue Query is declarative; you define the relationships between queries (parallelism, dependency, or pagination) rather than managing the imperative logic of execution, ensuring your cache remains consistent and your UI remains responsive.
Why exists
The Waterfall Problem. When you trigger an API call, wait for the result, and then trigger a second API call, you have created a waterfall. This is inefficient. Parallel queries exist to trigger independent requests simultaneously, cutting your total loading time to the duration of the single longest request rather than the sum of all requests.
The Race Condition Problem. Dependent queries—where Request B requires the result of Request A—are prone to race conditions. If you fetch Request B before Request A provides the necessary ID, the app crashes or fails. Dependent enabled chains exist to safely pause Request B until Request A is fully resolved and validated.
The UI Flicker Problem. In paginated lists, moving from Page 1 to Page 2 usually forces the existing data to be cleared and replaced with a loading spinner. This is jarring. keepPreviousData allows the UI to stay on Page 1 (showing the old data) while fetching Page 2 in the background, making the transition feel seamless and professional.
The Cache Synchronization Problem. Managing the invalidation and state of multiple related queries is complex. If you have a User query and a User-Settings query, they often need to be treated as a unit. Vue Query provides orchestration tools to keep these states aligned, preventing “stale data” from one query to clash with “fresh data” from another.
The Declarative Abstraction Problem. Manually checking isLoading states for five different variables across five different queries creates “if-else” hell in your components. Orchestration tools allow you to simplify your component logic, turning complex sync requirements into a clean, reactive configuration.
a. Parallel Queries with useQueries
Parallel queries are required when you need to fetch multiple independent resources at the same time. While you can simply call useQuery multiple times in a component, useQueries provides a unified interface for dynamic arrays of queries. This is especially useful when the number of queries is not known until runtime (e.g., a list of IDs to fetch).
// Fetching multiple users in parallel
const userIds = [1, 2, 3];
const results = useQueries({
queries: userIds.map((id) => ({
queryKey: ['user', id],
queryFn: () => fetchUser(id),
})),
});
// Accessing individual results
const user1 = results.value[0].data;
useQueries returns a reactive array of query results. This is highly efficient because it leverages the same underlying cache mechanism as useQuery. If one of the queries in the array has already been cached, it will be returned instantly, while the others continue to fetch, effectively merging cached and network states into a single reactive interface.
b. Dependent Queries via enabled Chains
A dependent query is a request that cannot start until a previous request has succeeded. In Vue Query, you implement this by passing a reactive computed property to the enabled option. This property evaluates to false until the dependency (e.g., the parent data) is ready, effectively “pausing” the dependent query.
// 1. Fetch the project
const { data: project } = useQuery({
queryKey: ['project', projectId],
queryFn: () => fetchProject(projectId),
});
// 2. Fetch tasks for that project (only when project is ready)
const { data: tasks } = useQuery({
queryKey: ['tasks', projectId],
queryFn: () => fetchTasks(project.value!.id),
// The 'enabled' option acts as the gatekeeper
enabled: computed(() => !!project.value),
});
This pattern prevents requests with undefined IDs or invalid parameters. Because enabled is reactive, as soon as project.value becomes truthy, Vue Query automatically triggers the task fetch. This declarative chain replaces complex watch or useEffect logic, ensuring that the dependency graph is always respected.
c. Paginated Queries with placeholderData
Pagination often leads to a poor user experience where the UI clears out completely between pages. The placeholderData: keepPreviousData option solves this by maintaining the data from the previous page in the data property while the new page is being fetched in the background.
const { data, isFetching } = useQuery({
queryKey: ['projects', { page }],
queryFn: () => fetchProjects(page),
// Keep the old data visible while new data loads
placeholderData: keepPreviousData,
});
When this is active, the isFetching flag becomes your most important tool. You can use it to apply a visual “dimming” effect to the list or show a subtle progress bar at the top of the container. The user sees the old content, knows something is updating, and then the content swaps out instantaneously once the new page arrives. This provides a “SPA-feel” without the jumpy loading states.
Complete Example Session
// ============================================
// PART 1: PARALLEL QUERIES
// ============================================
const { data: results } = useQueries({
queries: [
{ queryKey: ['posts'], queryFn: fetchPosts },
{ queryKey: ['users'], queryFn: fetchUsers },
],
});
// ============================================
// PART 2: DEPENDENT QUERY CHAIN
// ============================================
const { data: user } = useQuery({
queryKey: ['user'], queryFn: fetchUser
});
const { data: settings } = useQuery({
queryKey: ['settings'],
queryFn: () => fetchSettings(user.value.id),
enabled: computed(() => !!user.value),
});
// ============================================
// PART 3: PAGINATION WITH PLACEHOLDER DATA
// ============================================
const page = ref(1);
const { data, isPlaceholderData } = useQuery({
queryKey: ['items', page],
queryFn: () => fetchItems(page.value),
placeholderData: keepPreviousData,
});
// ============================================
// PART 4: MUTATION & INVALIDATION
// ============================================
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: updateItem,
onSuccess: () => {
// Invalidate the paginated list to force a refresh
queryClient.invalidateQueries({ queryKey: ['items'] });
}
});
// ============================================
// PART 5: PREFETCHING NEXT PAGE
// ============================================
watchEffect(() => {
if (page.value < 10) {
queryClient.prefetchQuery({
queryKey: ['items', page.value + 1],
queryFn: () => fetchItems(page.value + 1),
});
}
});
// ============================================
// PART 6: PARALLEL DEPENDENT ORCHESTRATION
// ============================================
// Combining both: Fetch multiple items, then fetch details for all
const { data: ids } = useQuery({ queryKey: ['ids'], queryFn: getIds });
const details = useQueries({
queries: computed(() => (ids.value || []).map(id => ({
queryKey: ['detail', id],
queryFn: () => fetchDetail(id),
enabled: !!ids.value
})))
});
// ============================================
// PART 7: ERROR HANDLING IN DEPENDENT QUERIES
// ============================================
// Use a computed to check for dependencies AND error states
enabled: computed(() => !!user.value && !userError.value)
// ============================================
// PART 8: CUSTOM PLACEHOLDER DATA
// ============================================
placeholderData: (previous) => previous || { items: [] }
// ============================================
// PART 9: THE STATUS FLAGS
// ============================================
// isFetching (true while loading new page)
// isPlaceholderData (true if showing old data)
// ============================================
// PART 10: DEBOUNCED PAGINATION
// ============================================
// Use a debounced ref for the page number to prevent
// hammering the API on rapid clicks
The example above demonstrated parallel fetching, dependent execution based on state, smooth pagination with existing data retention, and prefetching strategies.
Quick Reference
Orchestration Interfaces
| Interface | Input | Behavior |
|---|---|---|
useQueries | Array of options | Executes all queries in parallel |
enabled | boolean / computed | Blocks execution if false |
keepPreviousData | Option | Maintains old data during transitions |
Status Flags for Pagination
| Flag | Description |
|---|---|
isFetching | True when the new page is currently being fetched |
isPlaceholderData | True when showing previous data while loading new data |
isError | True if the current fetch failed |
Dependent Query Rules
| Rule | Requirement |
|---|---|
| Safety | Always check dependency is not null/undefined |
| Reactivity | Use computed for enabled to react to store/props changes |
| Ordering | Vue Query manages execution order once enabled |
Best Practices
✅ Do This:
// Bundle independent parallel calls
const results = useQueries({ queries: [...] }); // ✅
// Use computed for dependencies
enabled: computed(() => !!parentData.value) // ✅
// Always keep previous data for paginated UI
placeholderData: keepPreviousData // ✅
// Prefetch the next page for snappy navigation
queryClient.prefetchQuery({ queryKey: ['list', p+1] }); // ✅
❌ Don’t Do This:
// Create waterfalls by awaiting queries sequentially
const u = await fetchUser(); const p = await fetchPosts(u); // ❌
// Use raw boolean for enabled (not reactive)
enabled: !!parentData.value // (This won't re-run when data loads) // ❌
// Forget to handle loading states in pagination
// (Users won't know if the page is currently switching) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Waterfalls | Using await inside components for data | Use useQueries or independent useQuery calls |
| Ghost Dependencies | enabled not updating when dep changes | Always use computed(() => ...) for enabled |
| UI Flicker | Not using keepPreviousData | Set placeholderData: keepPreviousData |
| Invalidation Lag | Paginated data doesn’t update on mutation | Invalidate the whole paginated key: ['items'] |
Real-World Examples
1. Parallel Independent Fetch
useQueries({ queries: [{ queryKey: ['a'], queryFn: getA }, { queryKey: ['b'], queryFn: getB }] })
2. Dependent API Fetch
enabled: computed(() => !!userId.value)
3. Smooth Pagination
placeholderData: keepPreviousData
4. Conditional Prefetch
if (nextPage) queryClient.prefetchQuery(...)
5. Dynamic useQueries
queries: ids.map(id => ({ queryKey: ['item', id], queryFn: () => fetch(id) }))
6. Disabling Pagination on Specific Events
enabled: computed(() => !isEditing.value)
7. Composing status flags
const isLoading = computed(() => isFetching.value && !isPlaceholderData.value)
8. Stale-while-revalidate for lists
staleTime: 5000, placeholderData: keepPreviousData
9. Error handling in dependent query
enabled: computed(() => !!parent && !parentError.value)
10. Bulk Invalidation
queryClient.invalidateQueries({ queryKey: ['items'] }) // Clears all pages
Visual
Parallel vs. Sequential Fetching
┌──────────────────────────────────────────────────────────┐
│ SEQUENTIAL (Waterfall) PARALLEL (Optimal) │
│ │
│ Fetch User ──► [Wait] Fetch User ──┐ │
│ Fetch Posts ◄─ [Wait] Fetch Posts ─┤ │
│ ▼ │
│ Time: A + B Time: Max(A, B) │
└──────────────────────────────────────────────────────────┘
Dependent Query Lifecycle
┌──────────────────────────────────────────────────────────┐
│ DATA DEPENDENCY │
│ │
│ Parent Query [Status: Loading] ──► [Status: Success] │
│ │ │
│ Child Query [Status: Disabled] ─────────┘ │
│ [Status: Fetching] ◄────────┘ │
└──────────────────────────────────────────────────────────┘
Paginated Data Flow
┌──────────────────────────────────────────────────────────┐
│ PAGINATION UX │
│ │
│ Page 1 (Visible) ──► Click Page 2 │
│ │
│ Page 1 (Placeholder) ──► Fetching Page 2 (Background) │
│ │
│ Page 2 (Visible) ◄── Replace │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Parallelism | useQueries |
| Dependency | enabled: computed(() => ...) |
| Pagination | placeholderData: keepPreviousData |
| Waterfall Prevention | Use parallel execution |
| UX Stability | Avoid clearing data on navigation |
| Reactive Control | Always use computed for enabled |
Key takeaways:
- Stop waterfalls. Parallelize independent queries using
useQueries. If two queries don’t depend on each other, they should never be awaited sequentially . - Orchestrate with
enabled. Dependent queries rely on a gatekeeper. By passing acomputedvalue toenabled, you make the query reactive to the state of its parent dependency . - Pagination requires UX care. Always use
placeholderData: keepPreviousDatawhen navigating through paginated lists. It prevents the UI from jumping and makes the app feel like a single-page experience rather than a series of reloads . - Prefetching is your friend. When paginating, use
queryClient.prefetchQueryto load the next page before the user clicks, creating an instant navigation feel . - Combine flags for precision. Use
isFetchingandisPlaceholderDatato show specific UI states. Don’t hide the entire content; use a progress bar or dimmer instead . - Invalidate aggressively. When a mutation occurs in a paginated list, invalidate the root key (e.g.,
['items']) to ensure that all pages are marked stale and updated .
Remember: Complexity in data orchestration is a solved problem. Use useQueries for parallel requests, reactive enabled chains for dependent requests, and placeholderData for smooth paginated transitions to build interfaces that feel instantaneous and reliable.
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!