useHasMounted

Avoid weird SSR issues with this handy React hook. Know whether you're rendering on the client or server!

JSX
import { useState, useEffect } from 'react';

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

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

  return hasMounted;
}
JSX
const SomeClientSideOnlyComponent = () => {
  const hasMounted = useHasMounted();
  if (!hasMounted) {
    return null;
  }
  return <div>Client only!</div>;
};
Last Updated: