Dan Stroot Headshot

useHasMounted

1 min read

Published

Why

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

The trick here is that useEffect only triggers on the client side inside the browser. Smart right?

Usage

  
  
       
  
  const hasMounted = useHasMounted()

if (hasMounted) {
  // do stuff
}

Code

  
  
       
  
  import { useEffect, useState } from 'react'

export const useHasMounted = () => {
  const [hasMounted, setHasMounted] = useState(false)
  useEffect(() => {
    setHasMounted(true)
  }, [])

  return hasMounted
}