writing-react-effects

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Writing React Effects Skill

编写React Effects技能

Guides writing React components that avoid unnecessary
useEffect
calls.
指导编写避免不必要
useEffect
调用的React组件。

Core Principle

核心原则

Effects are an escape hatch for synchronizing with external systems (network, DOM, third-party widgets). If there's no external system, you don't need an Effect.
Effects是与外部系统(网络、DOM、第三方小部件)同步的逃生舱。如果没有外部系统交互,你不需要Effect。

Calculate Derived State During Rendering

在渲染期间计算派生状态

If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
Incorrect (redundant state and effect):
tsx
function Form() {
  const [firstName, setFirstName] = useState('First')
  const [lastName, setLastName] = useState('Last')
  const [fullName, setFullName] = useState('')

  useEffect(() => {
    setFullName(firstName + ' ' + lastName)
  }, [firstName, lastName])

  return <p>{fullName}</p>
}
Correct (derive during render):
tsx
function Form() {
  const [firstName, setFirstName] = useState('First')
  const [lastName, setLastName] = useState('Last')
  const fullName = firstName + ' ' + lastName

  return <p>{fullName}</p>
}
如果某个值可以通过当前props/state计算得出,不要将其存储在state中或在effect中更新它。在渲染时派生该值,以避免额外渲染和state漂移。不要仅响应props变化就在effects中设置state;优先选择派生值或键控重置。
错误示例(冗余状态和effect):
tsx
function Form() {
  const [firstName, setFirstName] = useState('First')
  const [lastName, setLastName] = useState('Last')
  const [fullName, setFullName] = useState('')

  useEffect(() => {
    setFullName(firstName + ' ' + lastName)
  }, [firstName, lastName])

  return <p>{fullName}</p>
}
正确示例(在渲染时派生):
tsx
function Form() {
  const [firstName, setFirstName] = useState('First')
  const [lastName, setLastName] = useState('Last')
  const fullName = firstName + ' ' + lastName

  return <p>{fullName}</p>
}