慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
React.js ~use()钩子用于缓存问题~
Ogasawara Ka · 2026-05-24 · via DEV Community
Cover image for React.js ~use() hook for Caching Problem~

Ogasawara Kakeru

此乃多数教程止步之处。然若汝欲尝试use()于客户端组件中创制一诺,则必遇隐微而恼人之弊。

// 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} />;
}

入全景模式 出全屏模式

fetchUser(userId)每渲染必返新承诺。React睹新承诺,复悬止,组件再渲染,造新承诺,复悬止,循环无已。

之用,不取数据,惟读其诺。此诺须于屡现之间,恒守其一。若每现辄造新诺,则永陷悬停之困。

何以固诺
道有数途,各适其构:

一、于上体或伺者中造诺

// 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>
  );
}

全幅模式入 退出全屏模式

async/await无需,此诺未决而承之。客组件以用之解其缚,主组件不更,故其诺之引固常。

二、用模块之缓存

客组件欲发之,当蓄其诺,俾后呼复得同引:

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} />;
}

入全景模式 出全景模式

同论必得同诺,无循环之患

勿于缓存包装中用异步

勿标缓存函数为异步。异步之辞必生新诺,纵返缓存之值。宜用同步函数,存原诺而返之。

3. 用数据获取之库

如TanStack Query或SWR之库,可自备缓存、去重、再验证之能。其早于use()之用,解更广之题——然亦增~13kB之gzip压缩及提供器之裹。若简以"取一次、显其果"之式,用五行缓存之函数(前述选项二),无额外依存亦可成事。此库之值,在于UI有长存之客户端状态,需常新之境:思仪表盘于标签聚焦时重取,分页之列,或应乐观更新相关查询之变。

四、用React之cache()于Server Components
React为Server Components备有内置之cache()函数。此函数可于单次服务器请求之期间内,将函数之返回值予以备忘:

import { cache } from "react";

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

切换全屏模式 退出全屏模式

多组件调用getUser("123") 同一渲染时,共享一 fetch。缓存限于请求,每新页加载即重置。

cache() 与 useMemo
二者皆可备忘。然 cache() 跨组件于服务器渲染(去重),而 useMemo 独于单组件跨重绘。cache() 适于数据获取,useMemo 适于计算。工不同,事各异。