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?
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>; }
Think about how cache memoizes the function calls with the same arguments.
The cache function memoizes the fetchUser call. So when called twice with the same userId, the fetch happens only once (console logs once), but the component renders twice with the cached data.
Choose the code snippet that correctly memoizes a fetch request using cache from React in Next.js.
Remember the correct import source for cache in React 18+ and Next.js 14+.
The cache function is imported from 'react' and wraps the async function to memoize it. Option A uses memo which is for components, not functions. Option A imports from 'next' which is incorrect; the correct import for Next.js navigation utilities is 'next/navigation'. Option A does not memoize.
Given this code, why does the fetch happen on every call despite using cache?
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>; }
Consider where the fetchData function is declared and how cache memoizes.
If fetchData is declared inside the component or function body, it is recreated on every render, so memoization is lost. It must be declared outside to persist memoization.
count after these memoized fetch calls?Analyze this code snippet. What will be the final value of count after both calls?
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();
Think about how cache memoizes calls with different arguments.
The memoized function runs once for each unique argument. Calls with the same argument reuse cached results. So count increments twice: once for id=1, once for id=2.
Choose the most accurate description of how cache memoizes requests in Next.js Server Components.
Recall how cache works in server components and argument-based memoization.
cache memoizes async functions by their arguments and keeps results across server renders, preventing duplicate fetches for the same inputs. It does not cache client-side or use localStorage.