reactjs / reactjs/react.dev

Running an effect only on update vs Strict mode

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

还没有人认领这个 Issue。

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

描述

I have written a variation of the useEffect hook that should only run on updates. I used a useRef hook to accomplish this the way the FAQ in the old docs recommends it here:

image

I couldn't find the same piece in the new documentation.

The problem is that the effect still runs on the initial render when strict mode is on:
https://codesandbox.io/s/delicate-lake-88phjz?file=/src/App.js

however it behaves correctly when the strict mode is off:
https://codesandbox.io/s/hungry-wright-tl7p43?file=/src/App.js

In the former example the message is logged to the console right away even though it shouldn't be.

The possible explanations I can think of are:

  1. I'm doing something wrong. Can you please point the mistake out for me?
  2. The old docs are off and this is not the right way to do it. In this case can you please let me know what the right way of achieving this behavior is?
  3. The strict mode is to blame. I do find it irritating at times, if I'm frank, but that's probably unlikely.

Can someone help me with this? Thanks a lot!

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先在链接的两个 CodeSandbox 示例中复现该行为,并比较 Strict Mode 和非 Strict Mode 的情况。结合旧的 FAQ 摘录阅读当前的 useEffect 和 useRef 文档;当清楚记录了跳过初始渲染的 effect 的推荐行为,或将 issue 解释为预期的 Strict Mode 行为时,即可视为完成。

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

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

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