| | |

Vue Query 13 ⚡ Resilience, Retries & Network Modes — Customizing retry backoff, select transforms, and offline behavior

⏱️ Estimated read: 11 min | |

Applications operating in the real world must navigate an unpredictable landscape of flaky Wi-Fi, server timeouts, and varying data structures. A truly resilient application does not simply crash when a request fails; it intelligently attempts to recover, differentiates between permanent and transient errors, and remains functional even when the user is disconnected from the internet. Vue Query provides a sophisticated suite of tools to manage these scenarios, moving beyond simple data fetching into the realm of network orchestration and data transformation.

At the core of this resilience is the retry mechanism. While many libraries offer a binary “success or failure” outcome, Vue Query implements an automated retry logic with exponential backoff. This ensures that temporary network glitches are resolved without user intervention. Furthermore, the library allows for granular control over which errors trigger a retry, preventing wasteful requests when a server explicitly rejects a call (such as a 401 Unauthorized or 404 Not Found). This logic is complemented by network modes, which define how queries should behave when the browser reports an offline status.

Beyond resilience, performance and data purity are managed through the select option. This feature allows developers to transform and memoize data at the cache layer before it ever reaches the component’s reactive state. By filtering or reshaping data early, components remain lean, and unnecessary re-renders are avoided because the component only “sees” the specific slice of data it requires. This chapter explores these advanced configurations, providing the blueprint for building high-durability Vue applications that provide a consistent experience regardless of network quality.

Key point: Vue Query builds application resilience by combining intelligent retry logic that skips non-recoverable errors, select transforms for optimized data delivery, and network modes that manage query execution during offline periods.


Why exists

The Flaky Connection problem. Mobile users frequently transition between cellular data and Wi-Fi, leading to “zombie” connections where a request starts but never finishes. Automated retries ensure that the application attempts to “self-heal” during these transitions without forcing the user to refresh the page.

The Server Overload problem. If a server is struggling, hitting it with a barrage of immediate retries can make the situation worse (a self-inflicted DDoS). Exponential backoff retries exist to give the server “breathing room” by increasing the time between attempts, allowing the infrastructure to recover.

The Client-Side Error trap. Retrying a 404 error is useless; the resource won’t suddenly appear on the second try. Distinguishing between 5xx (server) and 4xx (client) errors allows the application to fail fast when appropriate while remaining persistent when recovery is possible.

The Component Bloat problem. Components often receive massive JSON objects from an API but only need one or two fields. The select option exists to decouple the API’s data structure from the component’s needs, improving maintainability and reducing reactive overhead.

The Offline UX gap. Without network modes, an application might show an error state the moment a user enters an elevator. Vue Query’s “paused” state allows the application to wait gracefully for the connection to return, resuming fetches automatically when the user is back online.

The Re-render Performance wall. In large applications, if the global cache updates, every component listening to that cache might re-render. By using select, components only subscribe to specific slices of data, ensuring they only re-render when their specific requirements actually change.


a. Resilient Retries and Exponential Backoff

By default, Vue Query retries failed queries three times before showing an error. This is a sensible default for transient issues like temporary network loss. However, for a production application, you often need to customize this behavior based on the type of error encountered. The retry option can be a boolean, a number, or a function that receives the error and the failure count.

const { data, error } = useQuery({
  queryKey: ['user', id],
  queryFn: fetchUser,
  // Custom retry logic: only retry for 500-level server errors
  retry: (failureCount, error: any) => {
    if (error.response?.status === 404) return false; // Don't retry if not found
    if (failureCount < 3) return true; // Retry up to 3 times for other errors
    return false;
  },
  // Exponential backoff: 1s, 2s, 4s, 8s...
  retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 30000),
});

The retryDelay function is crucial for preventing server strain. By doubling the delay with each attempt (exponential backoff), you ensure that the client is persistent but polite. You can also set a cap (e.g., 30 seconds) so that the delay doesn’t become absurdly long.

In high-stakes environments, you might want to distinguish between “hard” errors and “soft” errors. A 401 Unauthorized should typically result in an immediate redirect to login rather than retries. Conversely, a 503 Service Unavailable is the perfect candidate for a persistent retry strategy, as it often indicates a temporary server restart or deployment in progress.


b. Data Transformation with the select Option

The select option is one of the most powerful performance features in Vue Query. It allows you to transform the data returned by the queryFn before it is returned to your component. This transformation is memoized; it only re-runs if the underlying data changes or if the select function reference itself changes.

const { data: userNames } = useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,
  // Transform a list of users into just a list of names
  select: (users) => users.map(user => user.name),
});

This is beneficial for two reasons. First, it keeps the component code clean. The component doesn’t need to know how to map or filter the API response; it just receives the final, usable result. Second, it optimizes re-renders. If other parts of the user object change (like a last-login timestamp) but the name stays the same, the component using the userNames select will not re-render because the structural sharing in Vue Query detects that the selected output is identical.

You can also use select to handle “Partial” data. If you have a query that fetches a full product list, but a specific component only needs the “On Sale” items, you can use select to filter that list at the cache level. This allows multiple components to use the same queryKey while seeing different perspectives of the data.


c. Network Modes and Offline Behavior

Vue Query recognizes that being “offline” is a state, not necessarily an error. It provides three “Network Modes” to control how queries behave when there is no internet connection. The default mode is online, which means queries will only fire if there is an active connection. If a query is triggered while offline, it is “paused” and will resume automatically once the connection is restored.

const { data } = useQuery({
  queryKey: ['settings'],
  queryFn: fetchSettings,
  // networkMode defaults to 'online'
  networkMode: 'always', // Ignore network status, always try to fetch
});

The three modes are:

  1. online (Default): Queries and mutations will pause if there is no connection. They resume when the user comes back online. This is best for most API-driven applications.
  2. always: The query always tries to fetch, regardless of the browser’s navigator.onLine status. This is useful for environments where the network status might be incorrectly reported or for local-only “APIs” (like service workers).
  3. offlineFirst: The query will try to fetch once, and if it fails due to network loss, it will behave like online mode and pause.

This behavior is particularly powerful when combined with staleTime. If a user goes offline but the data in the cache is still “fresh” (within the staleTime), Vue Query will serve that data immediately without even attempting a network request, ensuring a completely transparent experience during short connection drops.


Complete Example Session

// ============================================
// PART 1: THE DATA TYPE
// ============================================
interface User { id: number; name: string; email: string; role: string }

// ============================================
// PART 2: THE API FETCH
// ============================================
const fetchUsers = async (): Promise<User[]> => {
  const res = await fetch('/api/users');
  if (!res.ok) throw res; // Throw the whole response for status checking
  return res.json();
};

// ============================================
// PART 3: RESILIENT COMPONENT
// ============================================
import { useQuery } from '@tanstack/vue-query';

const { data: adminEmails, status, error } = useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,

  // ============================================
  // PART 4: SELECT TRANSFORMATION
  // ============================================
  // Only get emails of admin users
  select: (users) => users
    .filter(u => u.role === 'admin')
    .map(u => u.email),

  // ============================================
  // PART 5: CUSTOM RETRY LOGIC
  // ============================================
  retry: (count, err: any) => {
    // Stop retrying if the user isn't allowed to see this data
    if (err.status === 403) return false;
    return count < 3;
  },

  // ============================================
  // PART 6: BACKOFF STRATEGY
  // ============================================
  retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 10000),

  // ============================================
  // PART 7: OFFLINE HANDLING
  // ============================================
  networkMode: 'online', // Pause if Wi-Fi drops

  // ============================================
  // PART 8: STALE TIME FOR CACHING
  // ============================================
  staleTime: 1000 * 60 * 5, // 5 minutes of "freshness"
});

// ============================================
// PART 9: THE UI REACTION
// ============================================
// status === 'pending' && isPaused === true -> "Waiting for connection..."

// ============================================
// PART 10: MANUAL REFETCH ON DEMAND
// ============================================
// refetch() will ignore staleTime and force a call

The parts above demonstrate a complete lifecycle: defining data, fetching with built-in resilience, transforming for the UI, and managing the connection state.


Quick Reference

Retry Configurations

OptionTypeEffect
retryboolean | number | fnNumber of attempts or logic to decide
retryDelaynumber | fnTime between attempts (fixed or backoff)
retryOnMountbooleanShould it retry if the query fails on mount?

Network Modes

ModeBehaviorUse Case
onlinePauses if no networkMost standard web APIs
alwaysAlways tries to fetchService workers, Localhost, reliable LAN
offlineFirstFails once, then pausesHybrid apps with local fallbacks

Select Transform Benefits

FeatureDescription
OptimizationOnly triggers re-render if transformed data changes
CleanlinessKeeps mapping/filtering logic out of the template
MemoizationResult is cached until source data changes

Best Practices

✅ Do This:

// Skip retries for client errors (404, 401, 400)
retry: (cnt, err) => err.status !== 404 && cnt < 3               // ✅

// Use exponential backoff for server reliability
retryDelay: (attempt) => 1000 * 2 ** attempt                    // ✅

// Filter data in the select option, not the template
select: (data) => data.filter(item => item.active)              // ✅

// Define select functions outside the component for stability
const mySelect = (data) => data.slice(0, 10);                   // ✅

❌ Don’t Do This:

// Don't retry infinitely; it can crash the user's browser
retry: true // (Dangerous without limit)                      // ❌

// Don't use select for heavy side-effects
select: (data) => { window.alert('hi'); return data; }         // ❌

// Don't ignore isPaused status in your UI
// (User should know why the spinner isn't spinning)           // ❌

// Don't hardcode fixed retry delays for high-traffic APIs
retryDelay: 1000 // (Can lead to "thundering herd" problems)   // ❌

Common Pitfalls

PitfallWhy It HappensFix
Infinite SpinnernetworkMode is online and user is offlineCheck fetchStatus === 'paused' in UI
Select never updatesThe select function reference is unstableUse useCallback-like patterns or move out of component
Too many retriesretry set to high numberLimit to 2 or 3 for standard web apps
401s triggering retriesDefault retry logic is too broadAdd status-check logic to the retry function
High memory usageHeavy transformations inside selectKeep select functions pure and efficient

Real-World Examples

1. Custom Retry for Auth

retry: (failureCount, error) => error.status !== 401 && failureCount < 2

2. Exponential Backoff

retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000)

3. Data Transformation (Mapping)

select: data => data.map(u => u.username)

4. Filtering Inactive Users

select: data => data.filter(u => u.isActive)

5. Local Storage Network Mode

networkMode: 'always' // for data stored in IndexedDB or localStorage

6. Memoized Selection

const selectTopFive = (data) => data.slice(0, 5)

7. Handling 404s

retry: (count, err) => err.status !== 404

8. Paused UI State

<div v-if="isPaused">No internet. Retrying when online...</div>

9. Dynamic Retry Delay

retryDelay: () => (process.env.NODE_ENV === 'development' ? 500 : 2000)

10. Counting Array Size

select: data => data.length // Only re-render if the count changes

Visual

Exponential Backoff Visualization

TIME ───►
Attempt 1: [Fail] ── 1s Delay ──┐
                                │
Attempt 2: [Fail] ────── 2s Delay ──────┐
                                        │
Attempt 3: [Fail] ────────── 4s Delay ──────────┐
                                                │
Attempt 4: [Final Success!] ◄───────────────────┘

The Select Option Barrier

┌──────────────────────────────┐
│  API Response (Massive JSON) │
│  { id, name, bio, tags, ... }│
└──────────────┬───────────────┘
               │
      ┌────────▼────────┐
      │  select() hook  │  ◄── Transformation Logic
      └────────┬────────┘
               │
┌──────────────▼───────────────┐
│  Component State (Lean JSON) │
│  { name, tags }              │
└──────────────────────────────┘

Network Mode Logic Flow

┌─────────────────────────────────────────────────────────────┐
│  Is Browser Online?                                         │
│                                                             │
│  YES ──────────► Execute Fetch Immediately                 │
│                                                             │
│  NO  ──────────► Is networkMode 'online'?                   │
│                   │                                         │
│                   ├─ YES ──► Pause Fetch, wait for signal   │
│                   │                                         │
│                   └─ NO  ──► Execute Fetch (will likely fail)│
└─────────────────────────────────────────────────────────────┘

Summary

ItemValue
Retry Default3 attempts
Backoff DefaultExponential (starting at 1s)
Select ResultMemoized until data/queryKey change
Network Modeonline (pauses while offline)
Resilience Hookretry function
Optimization Hookselect function

Key takeaways:

  • Retries build invisible durability. By automating the recovery process for transient errors, you provide a smooth experience that feels robust to the user .
  • Exponential backoff is a “Good Citizen” pattern. It prevents your application from overwhelming a struggling server, allowing infrastructure time to recover .
  • Skip retries on logic errors. Status codes like 404 and 401 represent permanent states or required actions; retrying them wastes resources and delays error handling .
  • select is a performance multiplier. By reducing the amount of data a component subscribes to, you minimize re-renders and keep your UI layer decoupled from API shifts .
  • Offline is a status, not a failure. Using networkMode: 'online' ensures that your application pauses gracefully when the connection is lost, resuming only when success is possible .
  • Structural sharing prevents churn. Vue Query only updates component data if the result of the select function is structurally different from the last run .

Remember: A resilient application is one that knows when to fight (retry) and when to wait (pause). Combine smart retry logic with select transforms to build a Vue application that is both high-performance and geographically reliable.

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!