react-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React

React

Overview

概述

Comprehensive React skill covering component architecture, performance optimization, state management, data fetching, and modern React 19+ APIs. Prioritizes React Compiler compatibility, Server Components, and elimination of data fetching waterfalls.
When to use: Building React applications, optimizing performance, choosing state management, implementing data fetching, reviewing component architecture.
When NOT to use: Non-React frameworks, purely server-side rendering without React, static sites without interactivity.
全面覆盖组件架构、性能优化、状态管理、数据获取及现代React 19+ API的React技能指南。优先关注React Compiler兼容性、Server Components以及数据获取瀑布流消除。
适用场景: 构建React应用、性能优化、选择状态管理方案、实现数据获取、评审组件架构。
不适用场景: 非React框架、不使用React的纯服务端渲染、无交互的静态站点。

Quick Reference

快速参考

PatternAPI / ApproachKey Points
Data fetching
use(dataPromise)
Replaces useEffect+useState fetch pattern
Form handling
useActionState(action, init)
Built-in pending states and error handling
Optimistic UI
useOptimistic(state, updateFn)
Instant feedback while server processes
Non-urgent updates
useTransition()
Mark updates as interruptible
Effect events
useEffectEvent(fn)
Reactive values without re-triggering effects
Form pending status
useFormStatus()
Read parent form pending state from child component
Unique IDs
useId()
Hydration-safe IDs for accessibility
Server stateReact Query /
useSuspenseQuery
Caching, deduplication, background refetch
Client state (local)
useState
/
useRef
Single component or transient values
Client state (global)Zustand / ContextCross-component client-only state
Derived stateCompute during renderNever sync derived values with effects
Lazy initialization
useState(() => expensive())
Avoid eager computation on every render
Component typesPage, Feature, UIRoute entry, business logic, reusable primitives
MemoizationTrust React Compiler firstManual useMemo/useCallback only when needed
Ref as prop
ref
prop on function components
No
forwardRef
needed in React 19
Ref cleanupReturn function from ref callbackCleanup runs on detach instead of
null
call
Code splitting
React.lazy()
+ Suspense
Lazy-load heavy components
Parallel fetches
Promise.all()
Eliminate sequential await waterfalls
Request dedup
React.cache()
Per-request server-side deduplication
Abort server work
cacheSignal()
Cancel expensive async work when client disconnects
State preservation
<Activity>
Hide UI while keeping state mounted
模式API / 实现方式核心要点
数据获取
use(dataPromise)
替代useEffect+useState的获取模式
表单处理
useActionState(action, init)
内置等待状态与错误处理
乐观UI
useOptimistic(state, updateFn)
服务器处理期间提供即时反馈
非紧急更新
useTransition()
将更新标记为可中断
副作用事件
useEffectEvent(fn)
无需重新触发副作用即可访问响应式值
表单等待状态
useFormStatus()
从子组件读取父表单的等待状态
唯一ID
useId()
适用于可访问性的 hydration 安全ID
服务端状态React Query /
useSuspenseQuery
缓存、去重、后台重新获取
客户端状态(本地)
useState
/
useRef
单个组件或临时值
客户端状态(全局)Zustand / Context跨组件的客户端专属状态
派生状态渲染期间计算绝不要使用副作用同步派生值
延迟初始化
useState(() => expensive())
避免在每次渲染时执行昂贵计算
组件类型页面、功能、UI路由入口、业务逻辑、可复用基础组件
记忆化优先信任React Compiler仅在必要时手动使用useMemo/useCallback
作为属性的Ref函数组件上的
ref
属性
React 19中无需
forwardRef
Ref清理从Ref回调中返回函数清理操作在组件卸载时运行,而非调用
null
代码拆分
React.lazy()
+ Suspense
懒加载大型组件
并行获取
Promise.all()
消除顺序await导致的瀑布流
请求去重
React.cache()
每请求的服务端去重
终止服务端工作
cacheSignal()
客户端断开连接时取消昂贵的异步工作
状态保留
<Activity>
隐藏UI的同时保持状态挂载

Common Mistakes

常见错误

MistakeCorrect Pattern
Fetching data in useEffect with useStateUse the
use()
API or React Query for data fetching with built-in caching
Storing derived values in state and syncing with effectsCompute derived values during render; never use effects for state synchronization
Wrapping everything in useMemo and useCallbackTrust React Compiler first; only add manual memoization for expensive computations or memoized children
Using
array.sort()
which mutates state
Use
array.toSorted()
for immutable sorting to avoid unexpected re-renders
Using
&&
for conditional rendering
Use ternary
condition ? <Component /> : null
to avoid rendering falsy values like
0
Using Math.random() or Date for IDsUse
useId()
for hydration-safe unique identifiers
Putting reactive values in effect deps to read latest valueUse
useEffectEvent
to access latest values without re-triggering effects
Creating object literals as effect dependenciesHoist static objects outside the component or use primitive dependencies
Using
forwardRef
in React 19 projects
Pass
ref
directly as a prop;
forwardRef
is deprecated in React 19
Mutating props or state during renderFollow Rules of React for React Compiler compatibility: pure renders, no side effects
错误正确模式
在useEffect中结合useState获取数据使用
use()
API或React Query进行数据获取,二者均内置缓存功能
将派生值存储在状态中并通过副作用同步在渲染期间计算派生值;绝不要使用副作用进行状态同步
给所有内容包裹useMemo和useCallback优先信任React Compiler;仅在处理昂贵计算或记忆化子组件时添加手动记忆化
使用会改变状态的
array.sort()
使用
array.toSorted()
进行不可变排序,避免意外重渲染
使用
&&
进行条件渲染
使用三元表达式
condition ? <Component /> : null
,避免渲染
0
等假值
使用Math.random()或Date生成ID使用
useId()
生成hydration安全的唯一标识符
在副作用依赖中放入响应式值以读取最新值使用
useEffectEvent
访问最新值,无需重新触发副作用
将对象字面量作为副作用依赖将静态对象提升到组件外部,或使用原始类型依赖
在React 19项目中使用
forwardRef
直接将
ref
作为属性传递;React 19中
forwardRef
已被弃用
渲染期间修改属性或状态遵循React规则以兼容React Compiler:纯渲染、无副作用

Delegation

任务委托

  • Explore component architecture and identify performance bottlenecks: Use
    Explore
    agent to profile re-renders, analyze bundle size, and trace data fetching waterfalls
  • Implement React feature with proper patterns: Use
    Task
    agent to build components following Server Component, Suspense, and React 19 conventions
  • Design frontend architecture and state management strategy: Use
    Plan
    agent to structure component hierarchy, select state management, and plan data fetching approach
  • 探索组件架构并识别性能瓶颈:使用
    Explore
    工具分析重渲染情况、评估包大小并追踪数据获取瀑布流
  • 采用正确模式实现React功能:使用
    Task
    工具按照Server Component、Suspense及React 19规范构建组件
  • 设计前端架构与状态管理策略:使用
    Plan
    工具构建组件层级、选择状态管理方案并规划数据获取方式

References

参考资料

  • Component patterns, state management, and useEffect decisions
  • Performance optimization: waterfalls, bundles, and re-renders
  • Hooks, Server Actions, and React 19 APIs
  • React Compiler patterns and re-render optimization
  • Server-side rendering and React Server Components
  • Anti-patterns and troubleshooting guide
  • 组件模式、状态管理及useEffect决策
  • 性能优化:瀑布流、包大小与重渲染
  • Hooks、Server Actions及React 19 API
  • React Compiler模式与重渲染优化
  • 服务端渲染与React Server Components
  • 反模式与故障排查指南