useMounted (React)

Returns whether the current component is mounted. Useful for SSR stuff (e.g. with Next.js).

typescriptjavascript
import { useEffect, useState } from 'react'
 
const useMounted = (): boolean => {
  const [mounted, setMounted] = useState(false)
 
  useEffect(() => {
    setMounted(true)
  }, [])
 
  return mounted
}
import { useEffect, useState } from 'react'
 
const useMounted = () => {
  const [mounted, setMounted] = useState(false)
 
  useEffect(() => {
    setMounted(true)
  }, [])
 
  return mounted
}

Usage

typescriptjavascript
const Example = () => {
  const mounted = useMounted()
 
  return (
    <>
      <ServerSideRenderableStuff />
      {mounted ? <ComponentThatReliesOnWindow /> : null}
    </>
  )
}
const Example = () => {
  const mounted = useMounted()
 
  return (
    <>
      <ServerSideRenderableStuff />
      {mounted ? <ComponentThatReliesOnWindow /> : null}
    </>
  )
}
Created 02/04/21Updated 18/03/23
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here