Two parts of one page often need the same data: a greeting and a notes panel
both need the reader's profile. Passing it down as props works, but it couples
the two components to the page. The tool for sharing one lookup within one
request is React's cache():
loadProfile("ada") called twice while rendering one page runs
fetchProfile once; both callers get the same result. When the next request
arrives, the cache is empty again. That last part is the point: it's a cache
whose lifetime is one request, so it can't serve one reader's data to another.
Read, predict, run
The lab's page has a Greeting and a Notes component that both call
loadProfile(readerId). A third, RememberedNotes, uses a different helper
that stores the first profile it loads in a module variable:
JavaScript
let remembered = null;export async function loadProfileRemembered(readerId) { if (!remembered) remembered = await fetchProfile(readerId, "module variable"); return remembered;}
fetchProfile logs each database read. The page starts signed in as Ada.
Predict two things: how many reads the console shows for the first page, and
what each section shows after you follow Sign in as Grace.
Keep a Request Cache Inside Its RequestNext.js · 6 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
import Cases from "./Cases.jsx";
import { loadProfile, loadProfileRemembered } from "@/lib/profiles.js";
export const dynamic = "force-dynamic";
// Two parts of the page each need the profile.
async function Greeting({ readerId }) {
const profile = await loadProfile(readerId);
return <p>Hello, {profile.name}</p>;
}
async function Notes({ readerId }) {
const profile = await loadProfile(readerId);
return <p>Your notes: {profile.privateNote}</p>;
}
async function RememberedNotes({ readerId }) {
const profile = await loadProfileRemembered(readerId);
return <p>Remembered notes: {profile.privateNote}</p>;
}
export default async function Page({ searchParams }) {
// A stand-in for the signed-in reader, which would come from a session.
const { as } = await searchParams;
const readerId = as === "grace" ? "grace" : "ada";
return (
<main>
<h1>Keep a Request Cache Inside Its Request</h1>
<nav>
<Link href="/?as=ada">Sign in as Ada</Link>
<Link href="/?as=grace">Sign in as Grace</Link>
</nav>
<section>
<h2>With cache()</h2>
<Greeting readerId={readerId} />
<Notes readerId={readerId} />
</section>
<section>
<h2>With a module variable</h2>
<RememberedNotes readerId={readerId} />
</section>
<Cases />
</main>
);
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run(ids) {
const cache = new Map();
let reads = 0;
for (const id of ids)
if (!cache.has(id)) {
cache.set(id, id);
reads++;
}
return reads;
}
export const examples = [
[[1, 1, 2], 2],
[[], 0],
];
import { cache } from "react";
const profiles = {
ada: { name: "Ada", privateNote: "Ada's draft notes" },
grace: { name: "Grace", privateNote: "Grace's draft notes" },
};
async function fetchProfile(readerId, via = "cache()") {
console.log(`database read for ${readerId}, via ${via}`);
await new Promise((resolve) => setTimeout(resolve, 50));
return profiles[readerId];
}
// React's cache(): calls with the same argument during ONE request share a
// result. The next request starts with an empty cache.
export const loadProfile = cache((readerId) => fetchProfile(readerId));
// A module variable: it lives as long as the server process, across every
// request and every reader.
let remembered = null;
export async function loadProfileRemembered(readerId) {
if (!remembered) remembered = await fetchProfile(readerId, "module variable");
return remembered;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
The first page logs two reads: one via cache(), shared by Greeting and
Notes, and one via the module variable. After Sign in as Grace:
With cache() shows Hello, Grace and Grace's draft notes, after
one new read for Grace.
With a module variable still shows Ada's draft notes, with no read
at all. The variable was set during Ada's request and outlives it; every
later reader gets Ada's private notes.
The bug isn't the caching, it's the lifetime and the key: the variable lives as
long as the server process and ignores who is asking.
The failure to avoid
A module-level Map or variable outlives one request. If its key omits the
caller, or nothing ever clears it, a performance change becomes a data leak
between users, and one that tests with a single user never catch. Prefer
cache() for per-request sharing; keep anything longer-lived for public data,
or key it by everything the answer depends on.
The rule as a model
lib/contract.js models what cache() does inside one request: a fresh Map
per call, so repeated ids are read once:
JavaScript
export function run(ids) { const cache = new Map(); let reads = 0; for (const id of ids) if (!cache.has(id)) { cache.set(id, id); reads++; } return reads;}
It returns the number of reads: [1, 1, 2] needs 2, and [] needs 0.
The case table below the sections checks it.
Trace [1, 1, 2]: write the Map's contents and reads after each id.
Exercise
Extend the contract
Do not perform a lookup for null or undefined ids. Continue to deduplicate valid ids.
Edit lib/contract.js, then rerun the original cases. If the requested rule
changes an earlier result, update that expected value deliberately. Keep the
other cases. Add the acceptance cases to examples so the preview checks them too.
Input [null, 1, null, 1] must return 1.
Your working spaceNext.js · 6 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
import Cases from "./Cases.jsx";
import { loadProfile, loadProfileRemembered } from "@/lib/profiles.js";
export const dynamic = "force-dynamic";
// Two parts of the page each need the profile.
async function Greeting({ readerId }) {
const profile = await loadProfile(readerId);
return <p>Hello, {profile.name}</p>;
}
async function Notes({ readerId }) {
const profile = await loadProfile(readerId);
return <p>Your notes: {profile.privateNote}</p>;
}
async function RememberedNotes({ readerId }) {
const profile = await loadProfileRemembered(readerId);
return <p>Remembered notes: {profile.privateNote}</p>;
}
export default async function Page({ searchParams }) {
// A stand-in for the signed-in reader, which would come from a session.
const { as } = await searchParams;
const readerId = as === "grace" ? "grace" : "ada";
return (
<main>
<h1>Keep a Request Cache Inside Its Request</h1>
<nav>
<Link href="/?as=ada">Sign in as Ada</Link>
<Link href="/?as=grace">Sign in as Grace</Link>
</nav>
<section>
<h2>With cache()</h2>
<Greeting readerId={readerId} />
<Notes readerId={readerId} />
</section>
<section>
<h2>With a module variable</h2>
<RememberedNotes readerId={readerId} />
</section>
<Cases />
</main>
);
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
export function run(ids) {
const cache = new Map();
let reads = 0;
for (const id of ids)
if (!cache.has(id)) {
cache.set(id, id);
reads++;
}
return reads;
}
export const examples = [
[[1, 1, 2], 2],
[[], 0],
];
import { cache } from "react";
const profiles = {
ada: { name: "Ada", privateNote: "Ada's draft notes" },
grace: { name: "Grace", privateNote: "Grace's draft notes" },
};
async function fetchProfile(readerId, via = "cache()") {
console.log(`database read for ${readerId}, via ${via}`);
await new Promise((resolve) => setTimeout(resolve, 50));
return profiles[readerId];
}
// React's cache(): calls with the same argument during ONE request share a
// result. The next request starts with an empty cache.
export const loadProfile = cache((readerId) => fetchProfile(readerId));
// A module variable: it lives as long as the server process, across every
// request and every reader.
let remembered = null;
export async function loadProfileRemembered(readerId) {
if (!remembered) remembered = await fetchProfile(readerId, "module variable");
return remembered;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Deduplicating only helps for ids that can be looked up. null and undefined
aren't ids, so they never reach the cache.
Hint 2: a first step
Guard an id before asking the Map whether it has been loaded.
Show one solution
Replace the exported run function and any constants shown here; keep the
examples export underneath it. Compare the result with your own approach.
JavaScript
export function run(ids) { const cache = new Map(); let reads = 0; for (const id of ids) if (id != null && !cache.has(id)) { cache.set(id, id); reads++; } return reads;}
id != null is true for every value except null and undefined (the loose
!= covers both), so 0 and "" are still looked up, since they could be
real ids. The guard comes before cache.has, so a missing id is neither stored
nor counted.
Explain it without the code
Your app caches profiles in a module-level Map keyed by profile id. Write one
way that could still show the wrong data, and what you'd change.
Going further
Read the Next.js guide for the framework boundary around this rule.
The preview runs code-playpad's Next.js simulation. Real caching, hydration,
authentication and persistence require the real-server checks described on Day 7.
Completion is saved in this browser only. It does not measure mastery.