Bird
Raised Fist0
NextJSframework~20 mins

Request memoization in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Request Memoization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this memoized fetch in a Next.js Server Component?

Consider this Next.js Server Component that fetches user data with memoization. What will be rendered if the component is called twice with the same userId?

NextJS
import { cache } from 'react';

const fetchUser = cache(async (userId) => {
  console.log('Fetching user', userId);
  const res = await fetch(`https://api.example.com/users/${userId}`);
  return res.json();
});

export default async function User({ userId }) {
  const user = await fetchUser(userId);
  return <div>{user.name}</div>;
}
AThe console logs 'Fetching user' once, but the user name is rendered only once.
BThe console logs 'Fetching user' once, and the user name is rendered twice.
CThe console logs nothing, and the user name is rendered twice.
DThe console logs 'Fetching user' twice, and the user name is rendered twice.
Attempts:
2 left
💡 Hint

Think about how cache memoizes the function calls with the same arguments.

📝 Syntax
intermediate
2:00remaining
Which option correctly memoizes a fetch request in Next.js using React's cache?

Choose the code snippet that correctly memoizes a fetch request using cache from React in Next.js.

A
import { cache } from 'react';
const getData = cache(async (id) =&gt; {
  const res = await fetch(`/api/data/${id}`);
  return res.json();
});
B
import { memo } from 'react';
const getData = memo(async (id) =&gt; {
  const res = await fetch(`/api/data/${id}`);
  return res.json();
});
C
import { cache } from 'next/navigation';
const getData = cache(async (id) =&gt; {
  const res = await fetch(`/api/data/${id}`);
  return res.json();
});
D
import { cache } from 'react';
const getData = async (id) =&gt; {
  const res = await fetch(`/api/data/${id}`);
  return res.json();
};
Attempts:
2 left
💡 Hint

Remember the correct import source for cache in React 18+ and Next.js 14+.

🔧 Debug
advanced
2:00remaining
Why does this memoized fetch not cache results as expected?

Given this code, why does the fetch happen on every call despite using cache?

NextJS
import { cache } from 'react';

export default async function Page() {
  const fetchData = cache(async (url) => {
    const res = await fetch(url);
    return res.json();
  });
  const data1 = await fetchData('https://api.example.com/data');
  const data2 = await fetchData('https://api.example.com/data');
  return <div>{data1.value} - {data2.value}</div>;
}
ABecause the URL string is not a stable reference, so cache treats each call as different.
BBecause fetch is not memoized internally, so cache does not apply.
CBecause the fetchData function is redefined on every render, losing memoization.
DBecause the cache function only memoizes synchronous functions, not async ones.
Attempts:
2 left
💡 Hint

Consider where the fetchData function is declared and how cache memoizes.

❓ state_output
advanced
2:00remaining
What is the value of count after these memoized fetch calls?

Analyze this code snippet. What will be the final value of count after both calls?

NextJS
import { cache } from 'react';

let count = 0;
const fetchData = cache(async (id) => {
  count++;
  return { id };
});

async function run() {
  await fetchData(1);
  await fetchData(1);
  await fetchData(2);
}

run();
Acount is 2 because fetchData is called twice with unique arguments.
Bcount is 3 because fetchData is called three times.
Ccount is 1 because fetchData is memoized and called once.
Dcount is 0 because count++ is never executed.
Attempts:
2 left
💡 Hint

Think about how cache memoizes calls with different arguments.

🧠 Conceptual
expert
3:00remaining
Which statement best describes request memoization with React's cache in Next.js?

Choose the most accurate description of how cache memoizes requests in Next.js Server Components.

A<p><code>cache</code> memoizes functions globally but does not consider function arguments, so it caches only one result per function.</p>
B<p><code>cache</code> memoizes only client-side requests and resets on every server render.</p>
C<p><code>cache</code> memoizes requests by storing results in localStorage for offline use.</p>
D<p><code>cache</code> memoizes function calls by argument identity and persists results across server renders, avoiding repeated fetches for the same inputs.</p>
Attempts:
2 left
💡 Hint

Recall how cache works in server components and argument-based memoization.

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