[Suggestion]: Update useEffect cleanup example regarding mount
還沒有人認領這個 Issue。
- 主要語言
- JavaScript
- 星號
- 11.8k
- 分支
- 7.9k
- 平均合併
- 1 天 11 小時
- 30 天內合併 PR
- 11
描述
Summary
On the Synchronizing with Effects page under section "Step 3: Add cleanup if needed" it seems like the example should be updated along with adding some more explanation for how useEffect works when in Strict Mode.
Page
https://react.dev/learn/synchronizing-with-effects
Details
Consider the following code:
import { useEffect } from "react";
export default function App() {
return (
<div>
<h1>My App</h1>
<TestExample />
</div>
);
}
function TestExample() {
useEffect(() => {
console.log("run effect");
return () => {
console.log("cleanup");
};
}, []);
return <h2>Test example!</h2>;
}
From reading the documentation and the explanation for how components mount, unmount, and then mount again in Strict Mode I would expect this example to log "run effect", then log "cleanup", and then log "run effect". Instead it seems like the component is only mounting once and not doing the extra steps because it only logs "run effect" once and nothing else.
After experimenting and searching around, I think the issue is that React can tell that this component will never be unmounted so it does not bother with the extra steps of unmounting and remounting it in Strict Mode. Look at this updated example:
import { useEffect, useState } from "react";
export default function App() {
const [showTestExample, setShowTestExample] = useState(false);
return (
<div>
<h1>My App</h1>
<button onClick={() => setShowTestExample(!showTestExample)}>
Toggle TestExample
</button>
{showTestExample ? <TestExample /> : ""}
</div>
);
}
function TestExample() {
useEffect(() => {
console.log("run effect");
return () => {
console.log("cleanup");
};
}, []);
return <h2>Test example!</h2>;
}
Now the component can be toggled to render or be removed from the screen. It now behaves as expected- when clicking the button and adding the component, it console logs "run effect", then "cleanup", then "run effect". I am honestly not sure how the example given in the docs is working at all because it seems like that component will always be rendered. I think this behavior should be explained in the doc so readers can understand why sometimes they may see the mount/unmount/remount behavior and other times they may not. Please correct me if my understanding is wrong.
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 https://react.dev/learn/synchronizing-with-effects 中的 "Step 3: Add cleanup if needed" 部分開始,並使用 issue 中的範例重現所回報的 Strict Mode 行為。更新範例和說明,讓讀者了解 cleanup 和 remount 行為何時發生,然後根據這些範例驗證文件中描述的行為。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript, react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 42/100