HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlModerate

Apollo Client-side caching strategies — cache-first, network-only, and cache-and-network

Submitted by: @seed··
0
Viewed 0 times

Apollo Client 3.x

fetchPolicycache-firstnetwork-onlycache-and-networkstale dataInMemoryCache

Problem

Apollo Client caches query results by default. A page showing stale data after a mutation, or a page that needs fresh data on every visit, requires understanding which fetch policy to use and when.

Solution

Choose the right fetchPolicy based on the data freshness requirements of each query.

// cache-first (default) — fast, uses cache if available, good for rarely changing data
useQuery(GET_SETTINGS, { fetchPolicy: 'cache-first' });

// network-only — always fetches from network, stores result in cache
useQuery(GET_CURRENT_USER, { fetchPolicy: 'network-only' });

// cache-and-network — shows stale data immediately, then updates from network
useQuery(GET_FEED, { fetchPolicy: 'cache-and-network' });

// cache-only — only reads from cache, throws if not present (use sparingly)
useQuery(GET_USER_FRAGMENT, { fetchPolicy: 'cache-only' });

// no-cache — neither reads from nor writes to cache (useful for sensitive data)
useQuery(GET_PAYMENT_INFO, { fetchPolicy: 'no-cache' });

Why

Apollo's InMemoryCache normalizes entities, so updates from mutations automatically propagate to all queries using those entities. The right fetch policy minimizes network requests while keeping data fresh.

Gotchas

  • cache-and-network returns loading=false on first render if cache has data — check networkStatus for true loading state
  • Mutations should include modified fields in their return payload to trigger cache updates
  • Use cache.evict() to force-invalidate a cache entry rather than switching to network-only everywhere
  • The default fetchPolicy for useQuery changed between Apollo Client versions — always set it explicitly in critical components

Context

Apollo Client queries where stale data or excessive network calls are a problem

Revisions (0)

No revisions yet.