[Suggestion]: StrictMode confusion about ordering of the events
還沒有人認領這個 Issue。
- 主要語言
- JavaScript
- 星號
- 11.8k
- 分支
- 7.9k
- 平均合併
- 1 天 11 小時
- 30 天內合併 PR
- 11
描述
Summary
This thread comes really close to avoid repeating this question again.
However I still have some doubts about the chain of the events in the strict mode.
I will quote the answer which provide the most valuable feedback.
"The mental model for this is that React really does unmount the component, but when re-mounting the component we restore the previously used state instead of starting fresh, the way Fast Refresh does, or some future features will."
But if that's the case why the order of the events(rendering, setting state, effects etc) is different while running in strict mode and outside of it?
Here are the concrete examples:
- https://codesandbox.io/p/sandbox/2z4wq2. This sandbox runs inside a strict mode and by inspecting the console we can see that the order of the events is like this
render
state setter
render
state setter
effect
clean up
effect
The second render and state setter are dimmed out according to the documentation and that's fine. So at least on the surface it appears that react is triggering render function (and state setter) 2 times before moving to the effects.
- https://codesandbox.io/p/sandbox/93zfkw. This sandbox runs outside of the strict mode and there is a button to toggle the mounting of the component. If the component is mounted, unmounted and mounted again the order of the events is like this.
render
state setter
effect
clean up
render
state setter
effect
This example has the mental model I have always worked with and which is clear, so I would waste too much time on it since that's how React also behaves on production.
The question is, if react is really performing mounting, unmounting and remounting while is the order different?
To be honest I haven't noticed that this difference is making my code harder to reason about while working with StrictMode.
I would like to know the details, if possible. What does this approach help React achieve that original one does not?
Page
https://react.dev/reference/react/StrictMode
Details
I think it would be helpful to update the page to explain why the behavior in StrictMode is different than simply running mounting, unmounting and mounting again.
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 React StrictMode 參考頁面開始,將其目前的說明與連結的 issue 討論串及兩個 CodeSandbox 範例進行比較。釐清 StrictMode 中觀察到的 render、state、effect 與 cleanup 順序為何不同於個別的 mount-unmount-remount 週期,並更新頁面,讓說明能回答這項差異。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript, react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100