javascript
31 lines · 6 steps
Deduping data fetches with React cache in Next.js
Wrapping loaders in React's cache() means each request fetches a project once, even when many components ask for it.
Explained by
highlit
1import { cache } from 'react'
2import { notFound } from 'next/navigation'
3import { db } from '@/lib/db'
4
5export const getProject = cache(async (slug) => {
6 const project = await db.project.findUnique({
7 where: { slug },
8 include: {
9 owner: { select: { id: true, name: true, avatarUrl: true } },
10 _count: { select: { tasks: true, members: true } },
11 },
12 })
13
14 if (!project) notFound()
15
16 return project
17})
18
19export const getProjectMembers = cache(async (slug) => {
20 const project = await getProject(slug)
21
22 return db.member.findMany({
23 where: { projectId: project.id },
24 orderBy: { joinedAt: 'asc' },
25 select: {
26 id: true,
27 role: true,
28 user: { select: { id: true, name: true, avatarUrl: true } },
29 },
30 })
31})
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping a server-side loader in cache() memoizes it per request so repeated calls hit the database only once.
- 2Cached loaders compose cleanly — one can call another and still reuse the first's memoized result.
- 3Calling notFound() inside a loader lets data access and 404 routing live in the same place.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deduping-data-fetches-with-react-cache-in-next-js-explained-javascript-d4ba/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.