Skip to content

Module 5: Caching Strategies

📦 Module 5: Caching Strategies

In this module, we explore how Next.js ensures extreme performance by caching data at every layer of the stack.

🏗️ 1. The Mechanic: Request Memoization

If you fetch the same data in two different components during a single request, vanilla React would fetch it twice. Next.js automatically “memoizes” these fetches.

The Logic:

  • Component A calls fetch('/api/user').
  • Component B calls fetch('/api/user').
  • Result: The network call only happens once.

🏗️ 2. The Abstraction: Full-Route Cache & Data Cache

Next.js provides a sophisticated caching system that goes beyond simple memory.

The Four Layers:

  1. Request Memoization: Cache within a single server request.
  2. Data Cache: Cache data across multiple requests and users (Persistent).
  3. Full Route Cache: Cache the entire HTML/RSC payload for a static route.
  4. Router Cache: Cache in the user’s browser for instant navigation.

The Next.js Way (Manual Revalidation):

// Force this fetch to be cached for 1 hour
fetch('https://api.com/data', { next: { revalidate: 3600 } });

// Or, use a "Tag" to clear it manually from a Server Action
fetch('https://api.com/data', { next: { tags: ['posts'] } });

// Inside a Server Action:
revalidateTag('posts');

🧪 Professor’s Challenge: Dynamic vs Static

Task:

  1. Build a page that displays new Date().toLocaleTimeString().
  2. Run npm run build and npm run start.
  3. Note how the time never changes when you refresh! This is the Full Route Cache.
  4. Change the component to include cookies() or headers() and see how it becomes dynamic.