reactjs / reactjs/react.dev

Calling state setter with same value doesn't reliably work as documented

未關閉 適合新手
#5,215 0 則留言 9 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
1 天 11 小時
30 天內合併 PR
11

描述

Thank you for the very high standard of documentation on the React website.

There's a bit that's slightly misleading, though. The "functional updates" section of the useState documentation says:

If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.

However, if you watch calls to the component function doing the state update, it seems like a render occurs the first time you do that, because the component function gets called that first time. (Once it returns a bail-out means child components aren't called to rerender.) Subsequent times the component sets the same state value, even the component function isn't called (because of a separate "fast" bail-out).

That first time looks like a render to a dev who's read the documentation and expected setting the same value to be a no-op. That's confusing enough to have made @amsterdamharu file this closed bug report and to have made me, independently, come to github to write a bug report as well (but fortunately I found that one first).

Perhaps:

If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely (although the component function may be called, at least the first time).

...or something like that.

Then when developers see our component function get called even though we did setValue((v) => v);, we'll know it isn't a bug or our misunderstanding something; it's just part of the complexity of React (and there's probably a good reason for it).

Thanks.

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從連結的 useState 文件中的「functional updates」區段開始,檢視其中關於相同狀態值的說明。更新措辭,解釋元件函式可能會在第一次更新為相同值時被呼叫,而後續的重新渲染會被略過;當文件不再暗示該函式總是一個 no-op 時,此變更就完成了。

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

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
1/5
預估耗時
1 小時以內
活躍度
停滯
描述清晰度
描述清楚
新手友好度
68/100

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

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