Request memoization helps save time and resources by remembering data from previous identical function calls within the same request. It avoids asking the server for the same information multiple times.
Request memoization in NextJS
import { cache } from 'react'; const fetchUserData = cache(async (userId) => { const response = await fetch(`https://api.example.com/users/${userId}`); if (!response.ok) { throw new Error('Failed to fetch user data'); } return response.json(); });
The cache function wraps an async function to remember its results.
When called again with the same arguments, it returns the saved result instantly.
import { cache } from 'react'; // Example: Memoize a fetch with no parameters const fetchSiteSettings = cache(async () => { const response = await fetch('https://api.example.com/settings'); return response.json(); });
import { cache } from 'react'; // Example: Memoize fetch with parameters const fetchPost = cache(async (postId) => { const response = await fetch(`https://api.example.com/posts/${postId}`); return response.json(); });
import { cache } from 'react'; // Edge case: Calling with different arguments await fetchPost(1); // Fetches and caches post 1 await fetchPost(2); // Fetches and caches post 2 await fetchPost(1); // Returns cached post 1 instantly
This program fetches user data for user 1 twice and user 2 once. The second fetch for user 1 uses cached data, so it does not print the fetching message again.
import { cache } from 'react'; // Memoized fetch function const fetchUserData = cache(async (userId) => { console.log(`Fetching data for user ${userId}`); const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`); if (!response.ok) { throw new Error('Failed to fetch user data'); } return response.json(); }); async function runDemo() { console.log('First call for user 1:'); const user1First = await fetchUserData(1); console.log(user1First.name); console.log('Second call for user 1 (should be cached):'); const user1Second = await fetchUserData(1); console.log(user1Second.name); console.log('Call for user 2:'); const user2 = await fetchUserData(2); console.log(user2.name); } runDemo();
Time complexity: The first call takes normal fetch time; repeated calls with the same arguments are instant.
Space complexity: Cached results use memory proportional to the number of unique argument sets.
Common mistake: Forgetting that memoization caches results only for the exact same arguments.
Use memoization when data changes rarely and repeated requests happen with the same parameters.
Request memoization saves repeated fetches by remembering previous results.
Use Next.js cache to wrap async fetch functions easily.
It improves performance and reduces server load for repeated requests.