この解答例は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:

  1. We import useRef and useEffect from the React library.
  2. We create a function called useIsMounted.
  3. We declare a ref called isMountedRef with an initial value of true.
  4. We use the useEffect hook with an empty dependency array to set the value of isMountedRef.current to false when the component is unmounted.
  5. 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.