この解答例は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
useRefanduseEffectfrom the React library. - We create a function called
useIsMounted. - We declare a ref called
isMountedRefwith an initial value oftrue. - We use the
useEffecthook with an empty dependency array to set the value ofisMountedRef.currenttofalsewhen the component is unmounted. - We return the
isMountedRefso 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.