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.
Practice
Solution
Step 1: Understand request memoization concept
Request memoization stores the results of previous fetches to avoid repeating the same network calls.Step 2: Identify the effect on performance
By remembering previous results, it reduces server load and speeds up response times.Final Answer:
To save repeated fetches by remembering previous results -> Option BQuick Check:
Request memoization = Save repeated fetches [OK]
- Thinking memoization increases server requests
- Confusing memoization with disabling cache
- Assuming memoization slows down fetches
Solution
Step 1: Recall Next.js cache usage
Next.js provides acachefunction that wraps async functions to memoize their results.Step 2: Check correct syntax
The correct syntax iscache(async () => await fetch(...)), which matches const cachedFetch = cache(async () => await fetch('/api/data')).Final Answer:
const cachedFetch = cache(async () => await fetch('/api/data')) -> Option CQuick Check:
cache wraps async fetch function = const cachedFetch = cache(async () => await fetch('/api/data')) [OK]
- Placing cache inside async incorrectly
- Using non-existent fetch.cache method
- Calling cache.fetch which does not exist
getData()?
import { cache } from 'react';
const getData = cache(async () => {
console.log('Fetching data');
return await fetch('/api/data').then(res => res.json());
});
await getData();
await getData();Solution
Step 1: Understand cache behavior on repeated calls
Thecachefunction memoizes the async function result, so the fetch and console.log run only once.Step 2: Analyze the second call effect
On the second call, the cached result is returned without running the function body again, so no console.log output.Final Answer:
Fetching data -> Option AQuick Check:
cache memoizes, so console.log runs once [OK]
- Expecting console.log to run twice
- Thinking cache disables function execution
- Confusing cache with normal fetch calls
import { cache } from 'react';
const getData = async cache(() => {
return await fetch('/api/data').then(res => res.json());
});Solution
Step 1: Check cache usage syntax
Thecachefunction must wrap the async function, not be called inside the async declaration.Step 2: Identify the syntax mistake
Writingasync cache(() => ...)is invalid syntax; it should becache(async () => ...).Final Answer:
SyntaxError: 'cache' must wrap the async function, not be called inside it -> Option DQuick Check:
cache wraps async function syntax = SyntaxError: 'cache' must wrap the async function, not be called inside it [OK]
- Placing async before cache call incorrectly
- Assuming fetch is undefined without context
- Thinking cache is not imported
Solution
Step 1: Understand memoization with parameters
To memoize requests per unique URL, the cache must consider the URL argument to store separate results.Step 2: Use cache with parameterized function
Wrapping a function that takes URL as input withcachememoizes each unique URL separately.Final Answer:
Usecachewith a function that takes the URL as argument and memoizes internally -> Option AQuick Check:
cache with parameters memoizes per input [OK]
- Using single cache for all URLs causing wrong data
- Ignoring memoization for dynamic inputs
- Assuming cache disables dynamic fetching
Ready to prove it?
Pass the test and this pattern moves unknown
