Skip to main content
useHasMounted
@coinbase/cds-web@8.13.6
Returns a boolean indicating if the component has mounted.
Import
import { useHasMounted } from '@coinbase/cds-web/hooks/useHasMounted'
SourceView source code

useHasMounted should be used when conditionally rendering components or styles in SSR or SSG environments.

We recommend using useHasMounted whenever you use useBreakpoints or any other hooks that rely on the window object to conditionally render content. This combination can be used to prevent cumulative layout shifts (CLS). This is called two pass rendering and ensures that the component has been mounted and the window object is present before painting the DOM.

const { isPhone } = useBreakpoints();
const hasMounted = useHasMounted();

// in component render
{
hasMounted && isPhone && <TextHeadline as="h3">Welcome {username}!</TextHeadline>;
}

Basic usage

Loading...
Live Code
function Example() {
  const hasMounted = useHasMounted();

  return <TextHeadline>Component has {hasMounted ? 'mounted' : 'not mounted'}</TextHeadline>;
}

Preventing Hydration Mismatch

Loading...
Live Code
function Example() {
  const hasMounted = useHasMounted();
  const [currentTime, setCurrentTime] = useState('');

  useEffect(() => {
    // Only run client-side code after mounting
    if (hasMounted) {
      setCurrentTime(new Date().toLocaleTimeString());
    }
  }, [hasMounted]);

  return <TextHeadline>{hasMounted ? `Current time: ${currentTime}` : 'Loading...'}</TextHeadline>;
}

Is this page useful?

Coinbase Design is an open-source, adaptable system of guidelines, components, and tools that aid the best practices of user interface design for crypto products.