この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - React コーディング問題
14. implement useIsMounted()
import { useRef, useEffect } from 'react';const useIsMounted = () => { const isMountedRef = useRef(true); useEffect(() => { return () => { isMountedRef.current = false; }; }, []); return isMountedRef;};export default useIsMounted;
Explanation:
- We import
useRef
anduseEffect
from the React library. - We create a function called
useIsMounted
. - We declare a ref called
isMountedRef
with an initial value oftrue
. - We use the
useEffect
hook with an empty dependency array to set the value ofisMountedRef.current
tofalse
when the component is unmounted. - We return the
isMountedRef
so that it can be used in other parts of our code.
With this hook, we can easily check if the component is still mounted by using const isMounted = useIsMounted().current
. This will give us a boolean value of true
if the component is still mounted, and false
if it has been unmounted.