This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for React Coding Question on BFE.dev
14. implement useIsMounted()

Solution:

Here is a simple implementation of useIsMounted() custom hook:

import { useEffect, useRef } from 'react';

function useIsMounted() {
  const isMountedRef = useRef(false);

  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  return isMountedRef.current;
}

export default useIsMounted;

Usage: You can use the useIsMounted() hook in your component to check if the component is mounted:

import { useEffect } from 'react';
import useIsMounted from './useIsMounted';

function MyComponent() {
  const isMounted = useIsMounted();

  useEffect(() => {
    const fetchSomeData = async () => {
      const res = await fetch('https://api.example.com/data');
      if (!isMounted) {
        // Component has been unmounted, do not update state.
        return;
      }
      const data = await res.json();
      setState({ data });
    };

    fetchSomeData();

    return () => {
      // Cleanup logic
    };
  }, [isMounted]);

  // Render logic
}

In the above example, we check if the component is still mounted before updating the state with the fetched data. If the component is unmounted, we don't update the state and prevent any memory leaks or errors.