DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 19

The task is to create a useIsMounted hook to determine if a component is mounted. The boilerplate code:


import React from 'react';

export function useIsMounted(): () => boolean {
  // your code here
}


// to try your code on the right panel
// export App() component like below

// export function App() {
//   ...
//   return <div>BFE.dev</div>
// }

Enter fullscreen mode Exit fullscreen mode

The first step is to create a reference that holds the component state

const isMounted = useRef(false)
Enter fullscreen mode Exit fullscreen mode

The component is either going to be mounted or not. As a result, the only states are either true or false. When the component is mounted, the .current value of the ref is set to true when the app is rendered.

useEffect(() => {
  isMounted.current = true
})
Enter fullscreen mode Exit fullscreen mode

Then, the state is set to false before the app is rendered again.

return () => {
isMounted.current = false
}
Enter fullscreen mode Exit fullscreen mode

Finally, a function is returned to be able to call isMounted() in async code

return () => isMounted.current
Enter fullscreen mode Exit fullscreen mode

The final code looks like this:

import React, { useEffect, useRef} from 'react';

export function useIsMounted(): () => boolean {
  // your code here
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;

    return () => {
      isMounted.current = false;
    }
  }, [])
  return () => isMounted.current
}


// to try your code on the right panel
// export App() component like below

// export function App() {
//   ...
//   return <div>BFE.dev</div>
// }

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)