Is your app mounted in SSR ?

Ramees Salim

Ramees Salim / September 16, 2022

1 min read

Any server-side rendering is confusing and challenging to know whether you're rendering on the server or the client.

This hook helps us to know whether the app is mounted or not for rendering and avoiding black spots or blank pages.

Hook

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

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

  return hasMounted;
}

Usage

const Component = () => {
  const mounted = useHasMounted();

  if (!mounted) {
    return null;
  }

  return <div>rendered in client only!</div>
};