react-useeffect
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseYou Might Not Need an Effect
你可能不需要Effect
Effects are an escape hatch from React. They let you synchronize with external systems. If there is no external system involved, you shouldn't need an Effect.
Effects是React的一个逃生舱。它们让你与外部系统同步。如果没有涉及外部系统,你就不需要使用Effect。
Quick Reference
快速参考
| Situation | DON'T | DO |
|---|---|---|
| Derived state from props/state | | Calculate during render |
| Expensive calculations | | |
| Reset state on prop change | | |
| User event responses | | Event handler directly |
| Notify parent of changes | | Call in event handler |
| Fetch data | | |
| 场景 | 不要做 | 应该做 |
|---|---|---|
| 从props/state派生状态 | | 在渲染期间计算 |
| 昂贵的计算 | 使用 | |
| 当props变化时重置状态 | 使用带 | |
| 用户事件响应 | 监听state的 | 直接使用事件处理函数 |
| 通知父组件变化 | 调用 | 在事件处理函数中调用 |
| 获取数据 | 无清理的 | 带清理的 |
When You DO Need Effects
何时确实需要使用Effects
- Synchronizing with external systems (non-React widgets, browser APIs)
- Subscriptions to external stores (use when possible)
useSyncExternalStore - Analytics/logging that runs because component displayed
- Data fetching with proper cleanup (or use framework's built-in mechanism)
- 与外部系统同步(非React组件、浏览器API)
- 订阅外部存储(可能的话使用)
useSyncExternalStore - 组件显示时执行的分析/日志记录
- 带有适当清理的数据获取(或使用框架的内置机制)
When You DON'T Need Effects
何时不需要使用Effects
- Transforming data for rendering - Calculate at top level, re-runs automatically
- Handling user events - Use event handlers, you know exactly what happened
- Deriving state - Just compute it:
const fullName = firstName + ' ' + lastName - Chaining state updates - Calculate all next state in the event handler
- 为渲染转换数据 - 在顶层计算,会自动重新运行
- 处理用户事件 - 使用事件处理函数,你能确切知道发生了什么
- 派生状态 - 直接计算即可:
const fullName = firstName + ' ' + lastName - 链式状态更新 - 在事件处理函数中计算所有后续状态
Decision Tree
决策树
Need to respond to something?
├── User interaction (click, submit, drag)?
│ └── Use EVENT HANDLER
├── Component appeared on screen?
│ └── Use EFFECT (external sync, analytics)
├── Props/state changed and need derived value?
│ └── CALCULATE DURING RENDER
│ └── Expensive? Use useMemo
└── Need to reset state when prop changes?
└── Use KEY PROP on componentNeed to respond to something?
├── User interaction (click, submit, drag)?
│ └── Use EVENT HANDLER
├── Component appeared on screen?
│ └── Use EFFECT (external sync, analytics)
├── Props/state changed and need derived value?
│ └── CALCULATE DURING RENDER
│ └── Expensive? Use useMemo
└── Need to reset state when prop changes?
└── Use KEY PROP on componentDetailed Guidance
详细指南
- Anti-Patterns - Common mistakes with fixes
- Better Alternatives - useMemo, key prop, lifting state, useSyncExternalStore
- 反模式 - 常见错误及修复方案
- 更好的替代方案 - useMemo、key属性、状态提升、useSyncExternalStore