Coded Geekery

BlogAboutContact
BlogAboutContact

useHasMounted

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

useHasMounted
function useHasMounted() { const [hasMounted, setHasMounted] = React.useState(false); React.useEffect(() => { setHasMounted(true); }, []); return hasMounted; }

Why?

When dealing with a server-side rendered application (through frameworks like Nextjs or Gatsby, or any sort of SSR setup), it can be useful to know whether you're rendering on the server or the client.

For example: If you don't have a dynamic backend (eg. a Nextjs app), you won't know whether the user is authenticated or not. In that first pre-render, you should render a blank spot. When the client renders, you can fill it in, either with the user's avatar or a "Sign in" link.

Usage

  • How to use it

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

    Coded Geekery

    © 2021 Roger Stringer. All rights reserved.

    TwitterGitHubInstagram

    Stuff

    HomeAbout MeContact Me

    Not Playing

    Spotify