Bird
Raised Fist0
NextJSframework~10 mins

Request memoization in NextJS - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to memoize the fetch request using a simple cache object.

NextJS
const cache = {};

export async function fetchData(url) {
  if (cache[url]) {
    return cache[url];
  }
  const response = await fetch(url);
  const data = await response.json();
  cache[url] = [1];
  return data;
}
Drag options to blanks, or click blank then click option'
Adata
Bresponse
Curl
Dfetch
Attempts:
3 left
💡 Hint
Common Mistakes
Storing the response object instead of the parsed data.
Using the URL string as the cached value instead of the data.
2fill in blank
medium

Complete the React hook to memoize the fetch request result using useState and useEffect.

NextJS
import { useState, useEffect } from 'react';

export function useFetch(url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchData() {
      const response = await fetch(url);
      const json = await response.json();
      setData([1]);
    }
    fetchData();
  }, [url]);
  return data;
}
Drag options to blanks, or click blank then click option'
Aresponse
Bjson
Curl
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Setting state with the response object instead of JSON data.
Using the URL or existing state variable incorrectly.
3fill in blank
hard

Fix the error in this Next.js server component to memoize the fetch request result.

NextJS
import React from 'react';

const cache = new Map();

export default async function Page() {
  const url = 'https://api.example.com/data';
  if (cache.has(url)) {
    return <pre>{JSON.stringify(cache.get(url), null, 2)}</pre>;
  }
  const res = await fetch(url);
  const data = await res.json();
  cache.set(url, [1]);
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Drag options to blanks, or click blank then click option'
Acache
Bres
Curl
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Caching the response object instead of the parsed data.
Caching the URL string or the cache object itself.
4fill in blank
hard

Fill both blanks to create a memoized fetch function that caches results and returns cached data if available.

NextJS
const cache = {};

export async function memoFetch(url) {
  if ([1]) {
    return cache[url];
  }
  const response = await fetch(url);
  const data = await response.json();
  [2] = data;
  return data;
}
Drag options to blanks, or click blank then click option'
Acache[url]
Bresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the wrong variable for cache existence.
Assigning the wrong value to the cache.
5fill in blank
hard

Fill all three blanks to implement a React hook that memoizes fetch results and updates state only when data changes.

NextJS
import { useState, useEffect, useRef } from 'react';

export function useMemoFetch(url) {
  const [data, setData] = useState(null);
  const cache = useRef({});

  useEffect(() => {
    if (cache.current[url]) {
      setData(cache.current[[1]]);
      return;
    }
    async function fetchData() {
      const res = await fetch(url);
      const json = await res.json();
      cache.current[[2]] = json;
      setData(json);
    }
    fetchData();
  }, [[3]]);

  return data;
}
Drag options to blanks, or click blank then click option'
Aurl
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using the data state variable instead of URL for cache keys.
Missing the URL dependency in the effect hook.

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