Skip to content

A Request Cache

The Course
•
20 min study

The cache that made use work does more than stop repeated requests. Once a topic has loaded, it's instant next time, and you can start a request before the component that needs it even renders.

Cached topics React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It logs each request, answers after a delay, and can't // load topic 4, so you can see what happens when a request fails. const topics = [ { id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." }, { id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." }, { id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." }, { id: 4, title: "Broken topic", summary: "" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopicList() { console.log("request: topic list"); await wait(400); return topics.map(({ id, title }) => ({ id, title })); } export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(id === 3 ? 1200 : 500); if (id === 4) throw new Error("Topic 4 couldn't be loaded."); return topics.find((topic) => topic.id === id); } import { Suspense, useState } from "react"; import TopicCard from "./TopicCard.jsx"; import { getTopic, invalidate } from "./cache.js"; export default function App() { const [id, setId] = useState(1); const [version, setVersion] = useState(0); function refresh() { invalidate(`topic:${id}`); setVersion(version + 1); } return ( <main> <h1>Study Hub</h1> <div className="toolbar"> {[1, 2, 3].map((n) => ( <button key={n} aria-pressed={n === id} onClick={() => setId(n)} onMouseEnter={() => getTopic(n)}> Topic {n} </button> ))} <button onClick={refresh}>Refresh</button> </div> <Suspense fallback={<p className="muted">Loading topic…</p>}> <TopicCard key={version} id={id} /> </Suspense> </main> ); } import { fetchTopic, fetchTopicList } from "./api.js"; // One promise per request, reused on every render. use() needs this: a new // promise each render would mean a new request each render. const cache = new Map(); function cached(key, load) { if (!cache.has(key)) cache.set(key, load()); return cache.get(key); } export const getTopicList = () => cached("topics", fetchTopicList); export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id)); export function invalidate(key) { cache.delete(key); } import { use } from "react"; import { getTopic } from "./cache.js"; export default function TopicCard({ id }) { const topic = use(getTopic(id)); return ( <section className="panel"> <h2>{topic.title}</h2> <p>{topic.summary}</p> </section> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

The cache

JavaScript
const cache = new Map();

function cached(key, load) {
  if (!cache.has(key)) cache.set(key, load());
  return cache.get(key);
}

The first getTopic(1) starts the request and stores its promise. Every later call, from any component and any render, gets the same promise. Once it has resolved, use returns the value straight away, with no fallback:

JavaScript
export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id));

Predict

Clear the console. Click Topic 2, then Topic 1, then Topic 2 again. How many request lines do you see?

Check your prediction

One, for topic 2, or none if your pointer passed over the button first. Topic 1 was cached on the first render, and topic 2 is cached after its first load. Returning to either is instant.

Starting early

Each topic button has onMouseEnter={() => getTopic(n)}. Moving the pointer over a button starts its request, before the click. By the time you click, the data is often ready, and no fallback appears. Hover over Topic 3, the slow one, wait a second, then click it.

This is called preloading. Because the cache returns the same promise, starting a request early is harmless: the component reuses it.

Reloading

Refresh removes the current topic from the cache, then changes the TopicCard's key so it renders from scratch, calls getTopic again, and finds nothing cached: a new request. Real data libraries call this invalidation, and do it after a change is saved, or when data is older than a set time:

JavaScript
function refresh() {
  invalidate(`topic:${id}`);
  setVersion(version + 1);
}

What this cache doesn't do

This one is deliberately tiny. A production cache also needs to:

  • forget failures, so a rejected request can be retried (the checkpoint does this);
  • expire old entries, or limit how many it keeps;
  • share loading state across tabs, and refetch when you come back.

That's why most apps use TanStack Query, SWR or a framework's loader for this. Knowing the shape underneath helps you use them well.

Exercise

Preload the next topic

When a topic has loaded, start loading the next one (1 → 2, 2 → 3), so pressing the next button can reuse that request. It is instant only if the preload has finished before the click. Do it in TopicCard.

Your working space React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It logs each request, answers after a delay, and can't // load topic 4, so you can see what happens when a request fails. const topics = [ { id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." }, { id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." }, { id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." }, { id: 4, title: "Broken topic", summary: "" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopicList() { console.log("request: topic list"); await wait(400); return topics.map(({ id, title }) => ({ id, title })); } export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(id === 3 ? 1200 : 500); if (id === 4) throw new Error("Topic 4 couldn't be loaded."); return topics.find((topic) => topic.id === id); } import { Suspense, useState } from "react"; import TopicCard from "./TopicCard.jsx"; import { getTopic, invalidate } from "./cache.js"; export default function App() { const [id, setId] = useState(1); const [version, setVersion] = useState(0); function refresh() { invalidate(`topic:${id}`); setVersion(version + 1); } return ( <main> <h1>Study Hub</h1> <div className="toolbar"> {[1, 2, 3].map((n) => ( <button key={n} aria-pressed={n === id} onClick={() => setId(n)} onMouseEnter={() => getTopic(n)}> Topic {n} </button> ))} <button onClick={refresh}>Refresh</button> </div> <Suspense fallback={<p className="muted">Loading topic…</p>}> <TopicCard key={version} id={id} /> </Suspense> </main> ); } import { fetchTopic, fetchTopicList } from "./api.js"; // One promise per request, reused on every render. use() needs this: a new // promise each render would mean a new request each render. const cache = new Map(); function cached(key, load) { if (!cache.has(key)) cache.set(key, load()); return cache.get(key); } export const getTopicList = () => cached("topics", fetchTopicList); export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id)); export function invalidate(key) { cache.delete(key); } import { use } from "react"; import { getTopic } from "./cache.js"; export default function TopicCard({ id }) { const topic = use(getTopic(id)); return ( <section className="panel"> <h2>{topic.title}</h2> <p>{topic.summary}</p> </section> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Preloading another topic is synchronization with the server, not JSX to calculate. Use an effect after the current topic has loaded. Keep hooks at the top level and let the cache reuse any request already started.

Hint 2: a first step

Import useEffect. After reading the current topic with use, add an effect that depends on id. Only preload when there is a next topic (ids 1 and 2 here). A preload failure must be handled so it isn't an unhandled rejection.

Show one solution
JSX
import { use, useEffect } from "react";
import { getTopic } from "./cache.js";

export default function TopicCard({ id }) {
  const topic = use(getTopic(id));

  useEffect(() => {
    if (id < 3) {
      void getTopic(id + 1).catch(() => {
        // A speculative request failed. Selecting it still uses the normal error UI.
      });
    }
  }, [id]);

  return (
    <section className="panel">
      <h2>{topic.title}</h2>
      <p>{topic.summary}</p>
    </section>
  );
}

After topic 1 commits, its effect starts request: topic 2. Re-rendering the same topic doesn't restart the effect, and the cache prevents duplicate loads. The cache still needs invalidation to retry a rejected request, as the checkpoint demonstrates.

Was this article helpful?

Your response is saved on this device.