Dan Stroot

useHasMounted

When dealing with a server-side rendered application it can be useful to know when you are rendering on the client.

Date:


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

hookExample.js
const hasMounted = useHasMounted()
 
if (hasMounted) {
  // do stuff
}

Code

useHasMounted.js
import { useEffect, useState } from 'react'
 
export const useHasMounted = () => {
  const [hasMounted, setHasMounted] = useState(false)
  useEffect(() => {
    setHasMounted(true)
  }, [])
 
  return hasMounted
}

Sharing is Caring

Edit this page