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变化时重置状态 | 用 | |
| 响应用户事件 | 用 | 直接使用事件处理器 |
| 通知父组件变化 | 用 | 在事件处理器中调用 |
| 获取数据 | 无清理逻辑的 | 带清理逻辑的 |
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 component需要响应某个事件?
├── 用户交互(点击、提交、拖拽)?
│ └── 使用事件处理器
├── 组件出现在屏幕上?
│ └── 使用Effect(外部同步、分析上报)
├── Props/state变化且需要派生值?
│ └── 在渲染时计算
│ └── 开销大?使用useMemo
└── 当props变化时需要重置状态?
└── 在组件上使用KEY属性Detailed Guidance
详细指南
- Anti-Patterns - Common mistakes with fixes
- Better Alternatives - useMemo, key prop, lifting state, useSyncExternalStore
- 反模式 - 常见错误及修复方案
- 更好的替代方案 - useMemo、key属性、状态提升、useSyncExternalStore