reactjs / reactjs/react.dev

Third Rule of Hooks: "Side effects may only be caused in useEffect and event handlers"

未关闭
#3,560 5 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

I'd like to propose a third rule of hooks.

In the section "Advanced Guides > Strict Mode" it states that

Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state.

If I'm not mistaken, the inverse of this statement is that side effects based on a certain state of states shall be triggered in a useEffect, and that side effects from user interaction shall be triggered directly in the event handler. Everything else shall be side effect free. I think that adding this to the "rules of hooks" section makes it easier to remember and gives it much more visibility. I think the "variety of problems" will especially grow when concurrent mode is introduced. By having a "checklist" that can be used during code reviews etc. makes it easier to avoid this kind of problems.

Also one could maybe repeat the "Do not mutate state" rule there, cause this is still a very common problem and having it multiple times in the docs does no harm in my eyes.

What do you think?

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从链接的 Strict Mode 指南和 Rules of Hooks 部分开始。将提议的副作用指导和重复状态突变规则与现有文档进行比较;当措辞和放置位置达成一致,并且相关文档已更新时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。