Kosorikōsori alpha

useIsMounted

Check if a component is currently mounted.

Installation

Copy-paste the hook

Copy and paste the hook code in a .ts file.

import { useCallback, useEffect, useRef } from 'react';
 
/**
 * A custom hook that provides a way to check if a component is currently mounted.
 *
 * @returns An object containing a function `isMounted` that returns a boolean
 *
 * @example
 * const { isMounted } = useIsMounted();
 * isMounted();
 */
export const useIsMounted = () => {
  const isMounted = useRef(false);
 
  useEffect(() => {
    isMounted.current = true;
 
    return () => {
      isMounted.current = false;
    };
  }, []);
 
  return { isMounted: useCallback(() => isMounted.current, []) };
};

Usage

import { isMounted } from '~/hooks/use-is-mounted';
const { isMounted } = useIsMounted();
 
isMounted();

Details

State management

  • Uses useRef to mantain a mutable reference (isMounted.current) that persist for the full lifetime of the component.
  • The value of isMounted.current is update dyrectly in the useEffect hook.

Re-rendering behavior

  • The hook does not cause re-renders when the mounted state changes because it uses useRef. The value can be accessed without triggering a re-render.
  • This can be beneficial for performance, especially in scenarios where the mounted state is checked frequently.

Return value

  • Returns an object with a memoized callback function that returns the current value of isMounted.current. This allows for a consistent reference to the mounted state without causing re-renders.

On this page