Bird
Raised Fist0
NextJSframework~10 mins

Request memoization in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Request memoization
Start Request
↓
Check Cache for Request
↓
Return Cached
↓
Use Data
↓
Render Response
When a request comes in, the system first checks if the response is cached. If yes, it returns cached data. If no, it fetches fresh data, stores it in cache, then uses it.
Execution Sample
NextJS
import { cache } from 'react';

const fetchData = cache(async (url) => {
  const res = await fetch(url);
  return res.json();
});
This code memoizes fetchData so repeated calls with the same URL return cached results without refetching.
Execution Table
StepActionInput URLCache Hit?Data Fetched?Cache Updated?Output
1Call fetchData('https://api.example.com/data')https://api.example.com/dataNoYesYes{ data: ... }
2Call fetchData('https://api.example.com/data') againhttps://api.example.com/dataYesNoNo{ data: ... }
3Call fetchData('https://api.example.com/other')https://api.example.com/otherNoYesYes{ otherData: ... }
4Call fetchData('https://api.example.com/data') againhttps://api.example.com/dataYesNoNo{ data: ... }
💡 Requests stop fetching new data when cache hits occur for the same URL.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
cache{}{ 'https://api.example.com/data': { data: ... } }{ 'https://api.example.com/data': { data: ... } }{ 'https://api.example.com/data': { data: ... }, 'https://api.example.com/other': { otherData: ... } }{ 'https://api.example.com/data': { data: ... }, 'https://api.example.com/other': { otherData: ... } }
Key Moments - 3 Insights
Why does the second call to fetchData with the same URL not fetch data again?
Because the cache already has the data for that URL from step 1, so it returns cached data without fetching again, as shown in execution_table row 2.
What happens when fetchData is called with a new URL?
The function fetches fresh data and updates the cache with the new URL and data, as seen in execution_table row 3.
Does the cache ever clear automatically in this example?
No, the cache keeps stored data indefinitely in this example until the app restarts or cache is manually cleared.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the cache state after step 3?
AContains data for 'https://api.example.com/data' only
BContains data for both 'https://api.example.com/data' and 'https://api.example.com/other'
CContains data for 'https://api.example.com/other' only
DCache is empty
💡 Hint
Check the cache variable_tracker after step 3 showing both URLs stored
At which step does fetchData first avoid fetching data due to cache hit?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at execution_table column 'Cache Hit?' to find first 'Yes'
If we call fetchData('https://api.example.com/new') after step 4, what happens?
ACache hit, returns cached data
BReturns undefined
CFetches new data and updates cache
DThrows an error
💡 Hint
New URL not in cache, so fetchData fetches and caches new data
Concept Snapshot
Request memoization caches results of data fetching.
Use cache wrappers like React's cache() to store results.
Repeated calls with same input return cached data instantly.
New inputs trigger fresh fetch and cache update.
Improves performance by avoiding duplicate network calls.
Full Transcript
Request memoization in Next.js means saving the results of data fetching so that if the same request happens again, the app can reuse the saved data instead of fetching it again. This is done by wrapping the fetch function with a cache helper. When a request comes in, the app checks if the data for that request is already in cache. If yes, it returns the cached data immediately. If no, it fetches fresh data, saves it in cache, then returns it. This saves time and network resources. The example code shows how to memoize a fetch function using React's cache. The execution table traces calls to this function with different URLs, showing when data is fetched or returned from cache. The variable tracker shows how the cache object grows as new URLs are fetched. Key moments clarify why repeated calls with the same URL do not fetch again and what happens with new URLs. The quiz tests understanding of cache state and behavior. Overall, request memoization helps Next.js apps be faster and more efficient by reusing data when possible.

Practice

(1/5)
1. What is the main purpose of request memoization in Next.js?
easy
A. To increase the number of server requests
B. To save repeated fetches by remembering previous results
C. To disable caching for all requests
D. To make fetch requests slower

Solution

  1. Step 1: Understand request memoization concept

    Request memoization stores the results of previous fetches to avoid repeating the same network calls.
  2. Step 2: Identify the effect on performance

    By remembering previous results, it reduces server load and speeds up response times.
  3. Final Answer:

    To save repeated fetches by remembering previous results -> Option B
  4. Quick Check:

    Request memoization = Save repeated fetches [OK]
Hint: Memoization means remembering past results to avoid repeats [OK]
Common Mistakes:
  • Thinking memoization increases server requests
  • Confusing memoization with disabling cache
  • Assuming memoization slows down fetches
2. Which of the following is the correct way to memoize a fetch function in Next.js using the built-in cache?
easy
A. const cachedFetch = fetch.cache('/api/data')
B. const cachedFetch = async cache(() => fetch('/api/data'))
C. const cachedFetch = cache(async () => await fetch('/api/data'))
D. const cachedFetch = cache.fetch('/api/data')

Solution

  1. Step 1: Recall Next.js cache usage

    Next.js provides a cache function that wraps async functions to memoize their results.
  2. Step 2: Check correct syntax

    The correct syntax is cache(async () => await fetch(...)), which matches const cachedFetch = cache(async () => await fetch('/api/data')).
  3. Final Answer:

    const cachedFetch = cache(async () => await fetch('/api/data')) -> Option C
  4. Quick Check:

    cache wraps async fetch function = const cachedFetch = cache(async () => await fetch('/api/data')) [OK]
Hint: Use cache() to wrap async fetch functions correctly [OK]
Common Mistakes:
  • Placing cache inside async incorrectly
  • Using non-existent fetch.cache method
  • Calling cache.fetch which does not exist
3. Given this code snippet in Next.js, what will be logged on the second call to 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();
medium
A. Fetching data
B. Fetching data Fetching data
C. No output
D. Error: cache is not a function

Solution

  1. Step 1: Understand cache behavior on repeated calls

    The cache function memoizes the async function result, so the fetch and console.log run only once.
  2. 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.
  3. Final Answer:

    Fetching data -> Option A
  4. Quick Check:

    cache memoizes, so console.log runs once [OK]
Hint: cache runs function once, returns cached result later [OK]
Common Mistakes:
  • Expecting console.log to run twice
  • Thinking cache disables function execution
  • Confusing cache with normal fetch calls
4. Identify the error in this Next.js memoized fetch code:
import { cache } from 'react';

const getData = async cache(() => {
  return await fetch('/api/data').then(res => res.json());
});
medium
A. TypeError: cache is not a function
B. RuntimeError: fetch is not defined
C. No error, code works fine
D. SyntaxError: 'cache' must wrap the async function, not be called inside it

Solution

  1. Step 1: Check cache usage syntax

    The cache function must wrap the async function, not be called inside the async declaration.
  2. Step 2: Identify the syntax mistake

    Writing async cache(() => ...) is invalid syntax; it should be cache(async () => ...).
  3. Final Answer:

    SyntaxError: 'cache' must wrap the async function, not be called inside it -> Option D
  4. Quick Check:

    cache wraps async function syntax = SyntaxError: 'cache' must wrap the async function, not be called inside it [OK]
Hint: cache wraps async function, not inside async declaration [OK]
Common Mistakes:
  • Placing async before cache call incorrectly
  • Assuming fetch is undefined without context
  • Thinking cache is not imported
5. You want to memoize a fetch function in Next.js that depends on a dynamic URL parameter. Which approach correctly memoizes requests per unique URL?
hard
A. Use cache with a function that takes the URL as argument and memoizes internally
B. Use a single cached function without parameters for all URLs
C. Memoize only the first URL and ignore others
D. Do not use cache; fetch every time for dynamic URLs

Solution

  1. Step 1: Understand memoization with parameters

    To memoize requests per unique URL, the cache must consider the URL argument to store separate results.
  2. Step 2: Use cache with parameterized function

    Wrapping a function that takes URL as input with cache memoizes each unique URL separately.
  3. Final Answer:

    Use cache with a function that takes the URL as argument and memoizes internally -> Option A
  4. Quick Check:

    cache with parameters memoizes per input [OK]
Hint: Memoize functions with parameters to cache per input [OK]
Common Mistakes:
  • Using single cache for all URLs causing wrong data
  • Ignoring memoization for dynamic inputs
  • Assuming cache disables dynamic fetching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard