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 文件一併閱讀;當清楚記錄跳過初始 render 的 effect 所建議的行為,或將 issue 解釋為預期的 Strict Mode 行為時,即可視為完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
需要釐清
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。