useHasMounted

Detect whether a component has mounted on the client. Useful for avoiding hydration edge-cases.

useHasMounted returns a boolean flag indicating whether the component has mounted on the client. This is helpful to gate rendering that depends on browser APIs or values that differ between SSR and client (preventing hydration mismatches).

Code

import { useEffect, useState } from 'react';

export const useHasMounted = () => {
  const [hasMounted, setHasMounted] = useState(false);

  useEffect(() => {
    setHasMounted(true);
  }, []);

  return hasMounted;
};

Example

Not yet mounted

Usage

import { useHasMounted } from '@/hooks/use-has-mounted';

export function ClientOnly() {
  const hasMounted = useHasMounted();
  if (!hasMounted) return null;
  return <SomeBrowserOnlyComponent />;
}