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

推荐订阅源

C
Check Point Blog
美团技术团队
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
V
Visual Studio Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
云风的 BLOG
云风的 BLOG
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
WordPress大学
WordPress大学
月光博客
月光博客
宝玉的分享
宝玉的分享
小众软件
小众软件
MongoDB | Blog
MongoDB | Blog
Apple Machine Learning Research
Apple Machine Learning Research
A
About on SuperTechFans
J
Java Code Geeks
博客园_首页
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
N
Netflix TechBlog - Medium
Vercel News
Vercel News
博客园 - 聂微东

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~
Ogasawara Ka · 2026-05-20 · via DEV Community

Every React developer has written this code:

const [data, setData] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);

useEffect(() => {
  let cancelled = false;
  setIsLoading(true);

  fetchUser(id)
    .then((user) => {
      if (!cancelled) setData(user);
    })
    .catch((err) => {
      if (!cancelled) setError(err);
    })
    .finally(() => {
      if (!cancelled) setIsLoading(false);
    });

  return () => {
    cancelled = true;
  };
}, [id]);

Enter fullscreen mode Exit fullscreen mode

Three state variables. A cleanup flag. A dependency array. A race condition you have to think about every single time. And this is the correct version: most codebases skip the canceled flag and the error handling entirely.

This pattern is not wrong. It works. But it is boilerplate that exists because React had no built-in way to say "wait for this promise, then render." Every component that etches data had to reinvent the same loading/error/data state machine from scratch.

React 19 introduced use() to fix this. It is the first hook that can be called inside conditionals and loops, it integrates directly with Suspense, and it turns the fetch-then-setState pattern into a single line.

**What use() Does

use() reads a value from a resource at render time. The resource can be a Promise or a Context.

import { use } from "react";

// Read a promise - suspends until resolved
const user = use(userPromise);

// Read context - like useContext, but callable in conditionals
const theme = use(ThemeContext);

Enter fullscreen mode Exit fullscreen mode

That is the entire API. One function, two use cases.

When you pass a Promise, use() integrates with the nearest <Suspense> boundary. While the promise is pending, the component suspends. React shows the Suspense fallback. When it resolves, React re-renders with the resolved value. When it rejects, the nearest Error Boundary catches the error.

No useState. No useEffect. No isLoading. No setData. React handles all of it.

use() does not fetch data. It unwraps a promise that someone else created. The distinction matters.

**The Pattern It Replaces
Wrap the snippet from above into a component and add the obligatory loading/error guards:

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    /* ... fetch, cancelled flag, setState ... */
  }, [userId]);

  if (isLoading) return <Skeleton />;
  if (error) return <ErrorMessage error={error} />;
  if (!user) return null;

  return <ProfileCard user={user} />;
}

Enter fullscreen mode Exit fullscreen mode

Three state declarations, one effect, three conditional returns: all before you reach the actual UI. Every component that fetches data repeats this structure.

Here is the same component with use():

// Client Component - only the happy path
"use client";

import { use } from "react";

function UserProfile({ userPromise }: { userPromise: Promise<User> }) {
  const user = use(userPromise);
  return <ProfileCard user={user} />;
}

Enter fullscreen mode Exit fullscreen mode

// Server Component - creates the promise and defines the boundaries
import { Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";

export default function UserPage({ params }: { params: { id: string } }) {
  const userPromise = fetchUser(params.id);

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

Enter fullscreen mode Exit fullscreen mode

The loading state is handled by <Suspense>. The error state is handled by <ErrorBoundary> (from the react-error-boundarypackage). The component itself only contains the happy path - the code that runs when data is available. The state machine has been moved from your code into React's runtime.

Because UserPage is a Server Component, it does not re-render. The promise reference is created once and passed down as a stable prop, no caching gymnastics needed.

**Separation of Concerns
Notice how the component that uses the data (UserProfile) is separated from the component that initiates the fetch and defines the loading/error UI (UserPage). This is intentional. The consumer doesn't know where the promise came from or what to show while waiting.