惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Jina AI
Jina AI
雷峰网
雷峰网
T
Tailwind CSS Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
博客园 - 司徒正美
I
InfoQ
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
小众软件
小众软件
U
Unit 42
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
React.js ~use() hook for Caching Problem~
Ogasawara Ka · 2026-05-24 · via DEV Community
Cover image for React.js ~use() hook for Caching Problem~

Ogasawara Kakeru

This is where most tutorials stop. But if you try to use use() with a promise created inside a Client Component, you will hit a subtle and frustrating bug.

// Bug: creates a new promise on every render
function UserProfile({ userId }: { userId: string }) {
  const user = use(fetchUser(userId)); // new promise every render
  return <ProfileCard user={user} />;
}

Enter fullscreen mode Exit fullscreen mode

fetchUser(userId) returns a new Promise object on every render. React sees a new promise, suspends again, and the component re-renders, creates another new promise, suspends again, infinite loop.

use() does not fetch data. It reads a promise. The promise must have a stable identity across renders. If you create a new promise on every render, you get an infinite suspension loop.

How to Stabilize the Promise
There are several approaches, each suited to a different archtecture:

1. Create the promise in a parent component or Server Component

// Server Component - promise created once, stable across renders
export default function UserPage({ params }: { params: { id: string } }) {
  const userPromise = fetchUser(params.id);

  return (
    <Suspense fallback={<Skeleton />}>
      <UserProfile userPromise={userPromise} />
    </Suspense>
  );
}

Enter fullscreen mode Exit fullscreen mode

No async/await needed, the promise is passed down unresolved. The Client Component unwraps it with use(). Server Components don't re-render, so the promise reference is inherently stable.

2. Use a module-level cache

For Client Components that need to initiate fetches, cache the promise so the same reference is returned on subsequent calls:

const cache = new Map<string, Promise<User>>();

function fetchUserCached(id: string): Promise<User> {
  if (!cache.has(id)) {
    cache.set(id, fetchUser(id));
  }
  return cache.get(id)!;
}

function UserProfile({ userId }: { userId: string }) {
  const user = use(fetchUserCached(userId));
  return <ProfileCard user={user} />;
}

Enter fullscreen mode Exit fullscreen mode

Same arguments produce the same promise reference. No infinite loop.

Avoid async in Cache Wrappers

Do not mark your cache function as async. The async keyword always creates a new promise, even if you return a cached value. Use a synchronous function that stores and returns the original promise object.

3. Use a data fetching library

Libraries like TanStack Query or SWR handle caching, deduplication, and revalidation out of the box. They predate use() and solve a much broader problem - but they also add ~13kB gzipped and a provider wrapper. For a simple "fetch once, display result" pattern, use() with a 5-line cache function (option 2 above) does the job without the extra dependency. The library earns its keep when your UI has long-lived client state that needs to stay fresh: think dashboards that refetch on tab focus, lists with pagination, or mutations that should optimistically update related queries.

4. Use React's cache() in Server Components
React provides a built-in cache() function for Server Components. It memoizes a function's return value for the lifetime of a single server request:

import { cache } from "react";

const getUser = cache(async (id: string): Promise<User> => {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
});

Enter fullscreen mode Exit fullscreen mode

Multiple components calling getUser("123") during the same render will share one fetch. The cache is scoped to the request, it resets on every new page load.

cache() vs. useMemo
Both memoize. But cache() works across components in a server render (deduplication), while useMemo works within a single component across re-renders. cache() is for data fetching. useMemo is for computations. Different tools, different jobs.