Coded Geekery

BlogWritingAboutContact
BlogWritingAboutContact

useHasMounted

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

const 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> };

    Not Playing

    Spotify

    Coded Geekery

    TwitterGitHubInstagramgumroadbuymeacoffee

    Stuff

    HomeAbout MeContact Me

    © 2022 Roger Stringer. All rights reserved.