Frontend Patterns

Pattern

Stale-While-Revalidate

Show cached data immediately while fetching fresh data in the background.

Stale-While-Revalidate

Problem

Users see loading spinners every time they revisit a page, even when cached data exists. Interfaces feel slow because they wait for fresh data before showing anything, despite having perfectly usable cached information. Users must choose between seeing instant but potentially stale data or waiting for fresh data, creating a false trade-off between speed and freshness.

Solution

Show cached data immediately while fetching fresh data in the background. This balances responsiveness with freshness by providing instant feedback that updates when new data arrives.

Example

This demonstrates showing cached data immediately while fetching fresh data in the background, balancing instant responsiveness with data freshness for better perceived performance.

const { data } = useQuery('todos', fetchTodos, {
  staleTime: 5000,         // Consider fresh for 5s - won't refetch during this time
  cacheTime: 30000,        // Keep in cache for 30s after unused
  refetchOnMount: 'always' // Always check for updates when component mounts
});

// Returns cached data immediately while revalidating in background
// UI shows instant feedback, then updates when fresh data arrives

Benefits

  • Provides instant feedback by showing cached data immediately.
  • Balances speed and freshness without forcing users to choose.
  • Improves perceived performance dramatically.
  • Keeps data fresh without sacrificing responsiveness.

Tradeoffs

  • Can show stale data temporarily, potentially confusing users.
  • Requires cache management and invalidation strategies.
  • May cause UI flashing when fresh data replaces cached data.
  • Needs careful configuration of stale and cache time settings.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.