Effect cleanup potential issue in React 17 for mutable value inside effect
還沒有人認領這個 Issue。
- 主要語言
- JavaScript
- 星號
- 11.8k
- 分支
- 7.9k
- 平均合併
- 1 天 11 小時
- 30 天內合併 PR
- 11
描述
In React 17, the effect cleanup function always runs asynchronously — for example, if the component is unmounting, the cleanup runs after the screen has been updated.
In the changelog React team has highlighted a potential issue and solution for this:
Problematic Code:
useEffect(() => {
someRef.current.someSetupMethod();
return () => {
someRef.current.someCleanupMethod();
};
});
Solution suggested by the React team:
The problem is that
someRef.currentis mutable, so by the time the cleanup function runs, it may have been set to null. The solution is to capture any mutable values inside the effect.
useEffect(() => {
const instance = someRef.current;
instance.someSetupMethod();
return () => {
instance.someCleanupMethod();
};
});
While the above solution works in most cases, I have created a custom hook, where this solution is problematic:
function useMountEffect(funcForMount, funcForUnmount) {
const funcRef = useRef();
funcRef.current = { funcForMount, funcForUnmount };
useEffect(() => {
funcRef?.current?.funcForMount?.();
return () => funcRef?.current?.funcForUnmount?.();
}, []);
}
In the above example, I explicitly don't want to capture the mutable value, otherwise, I'll have to re-run the effect when funcForUnmount changes.
The reason to create the hook in this way is to have the freedom to call the function only on mount / unmount without worrying about stale closure and dependency array.
Update:
I have found one approach for useMountEffect
function useMountEffect(funcForMount, funcForUnmount) {
const isMounted = useRef();
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
useEffect(() => {
if (!isMounted.current) {
isMounted.current = true;
funcForMount?.();
}
return () => !isMounted.current && funcForUnmount?.();
});
}
But the major questions here are:
- How can the
ref.currentgo null between unmount and cleanup call in React 17? - Who is setting the value null? Is it react which can set
ref.currentto null? Or, is it the user who can change in between? - If a user can change in between how is this possible? Why was it not an issue prior to React 17?
The reason to raise this issue for docs is that the line The problem is that someRef.current is mutable, so by the time the cleanup function runs, it may have been set to null. is unclear and raises a lot of questions in the mind.
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 issue 中連結的 React 17 changelog 部分開始,並將其中的說明與回報的 useMountEffect 範例進行比較。釐清誰可以將 ref.current 設為 null、cleanup 何時執行,以及為什麼 timing 在 React 17 中發生了變更。完成的標準是文件回答所列問題,且不會讓 mutable ref 的行為產生歧義。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript, react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100