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:
- Request Memoization: Cache within a single server request.
- Data Cache: Cache data across multiple requests and users (Persistent).
- Full Route Cache: Cache the entire HTML/RSC payload for a static route.
- 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:
- Build a page that displays
new Date().toLocaleTimeString(). - Run
npm run buildandnpm run start. - Note how the time never changes when you refresh! This is the Full Route Cache.
- Change the component to include
cookies()orheaders()and see how it becomes dynamic.