[Suggestion]: Update useEffect cleanup example regarding mount
まだ誰も着手していません。
- 主要言語
- JavaScript
- スター
- 11.8k
- フォーク
- 7.9k
- 平均マージ
- 1日 11時間
- マージ済み PR(30日)
- 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 にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- 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