Frontend Patterns

Pattern

Query Caching

Store fetched data to avoid redundant network requests and improve performance.

Query Caching

Problem

Every component mounting or re-rendering triggers new network requests for the same data. Users see loading spinners repeatedly for information they’ve already fetched moments ago. Navigating between pages or toggling UI elements causes the app to refetch identical data, wasting bandwidth and making the app feel sluggish. The same API calls fire dozens of times during a single user session.

Solution

Store fetched data in memory to avoid redundant requests for the same information. This improves performance and reduces server load while requiring strategies to keep cached data fresh.

Example

This example shows configuring query caching with specific time windows, keeping data in cache for 5 minutes but considering it stale after 1 minute.

const { data } = useQuery('users', fetchUsers, {
  // Keep data in cache for 5 minutes after last use
  cacheTime: 5 * 60 * 1000,
  // Data is fresh for 1 minute, then background refetch occurs
  staleTime: 1 * 60 * 1000
});

Benefits

  • Dramatically improves performance by eliminating redundant network requests.
  • Reduces server load and bandwidth usage.
  • Makes UI feel instant when displaying previously fetched data.
  • Enables offline-first experiences with cached data.

Tradeoffs

  • Can show stale data if cache invalidation isn’t properly configured.
  • Adds memory overhead to store cached responses.
  • Requires strategies for determining when to refetch versus using cache.
  • Can make debugging harder when cached data doesn’t match server state.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.