写 React 时你会注意哪些最佳实践
When coding React, what are some best practices that you keep in mind
这是开放题,答「有取舍的清单」比列一堆规则好。按重要性给六条:
- 不可变更新。永远造新对象/新数组, 不就地改 —— 否则 React 比引用发现不了变化,界面不更新。这是 React 里最常见的 bug 来源。
- 能算出来的别放 state。派生数据当场算, 不要用
useEffect同步两份数据 —— 同一个事实存两份必然会不一致。 - state 放在「刚好够用」的那一层。提太高造成 drilling 和多余渲染, 提太低兄弟拿不到。
- effect 里建立的东西一定要清理。定时器、监听器、订阅、在途请求。判别法:effect 里出现
setInterval/addEventListener/subscribe/fetch,就一定要return。 - 列表 key 用稳定业务 id,不用 index。
- 先测量再优化。别默认给所有东西套
useMemo。
再补两条工程上的:组件保持小而专一 (一个组件干一件事);用 TypeScript—— props 的形状是组件的契约, 写下来比靠记忆可靠。
如果面试官想听更具体的, 可以说: 「我会开着 eslint-plugin-react-hooks,不用注释关掉exhaustive-deps 警告—— 它几乎每次都是对的, 想绕过它通常说明该重构了。」 这条很能体现实战经验。
This is an open question, and a list with trade-offs beats a pile of rules. Six, most important first:
- Update immutably. Always build a new object or array, never edit in place — otherwise React compares references, sees nothing changed, and the UI does not update. This is the single most common source of bugs in React.
- If you can compute it, do not store it in state. Derive it on the spot; do not use
useEffectto keep two copies in sync — one fact stored twice will drift. - Keep state at the lowest level that works. Too high and you get prop drilling and wasted renders; too low and siblings cannot reach it.
- Anything an effect sets up has to be torn down. Timers, listeners, subscriptions, in-flight requests. The test: if the effect contains
setInterval,addEventListener,subscribeorfetch, it mustreturnsomething. - Use stable business ids as list keys, not the index.
- Measure before optimising. Do not wrap everything in
useMemoby default.
Two more on the engineering side: keep components small and single-purpose (one component, one job); and use TypeScript — the shape of the props is the component’s contract, and writing it down beats remembering it.
If the interviewer wants something more specific, you can say: “I keep eslint-plugin-react-hooks on and I do not silence the exhaustive-deps warning with a comment — it is right almost every time, and wanting to get around it usually means the code needs restructuring.” That one really shows hands-on experience.