Request Memoization in NextJS
🚀 Request Memoization in Next.js
Request Memoization in Next.js helps optimize API calls by caching responses to prevent unnecessary re-fetching. This improves performance by reducing network requests and speeding up page loads.
📌 1. Why Use Request Memoization?
✔️ Avoid duplicate requests for the same data
✔️ Reduce API load and server costs
✔️ Improve performance by caching responses
✔️ Optimize SSR & ISR data fetching
📌 2. Memoization with React's useMemo() (Client-Side)
For client-side rendering, use useMemo() to cache fetched data.
🔹 Example: Memoizing API Response in CSR
import useSWR from "swr";const fetcher = (url) => fetch(url).then((res) => res.<p>Failed to load<pre>{JSON.stringify(data, null, 2)}</pre>;}
✅ Avoids redundant API calls per request
✅ Cache resets on server restart
📌 7. Comparison of Request Memoization Methods
| Method | Use Case | Client/Server | Cache Duration |
|---|---|---|---|
useMemo() | Prevent re-fetching in React components | Client | Until re-render |
fetch() with cache: 'force-cache' | Cache API responses in App Router | Server | Until next build |
lru-cache | Cache API responses in API routes | Server | Configurable |
SWR | Automatic caching & revalidation | Client | Configurable |
getServerSideProps() cache | Memoizing in SSR | Server | Until server restarts |
🚀 Conclusion
✅ Use useMemo() for simple client-side memoization
✅ Use fetch() { cache: 'force-cache' } for server memoization
✅ Use lru-cache in API routes for controlled caching
✅ Use SWR for automatic client-side caching