useMounted (React)

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

typescript
      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

typescript
      const Example = () => {
  const mounted = useMounted()
 
  return (
    <>
      <ServerSideRenderableStuff />
      {mounted ? <ComponentThatReliesOnWindow /> : null}
    </>
  )
}
    
      const Example = () => {
  const mounted = useMounted()
 
  return (
    <>
      <ServerSideRenderableStuff />
      {mounted ? <ComponentThatReliesOnWindow /> : null}
    </>
  )
}
 
    
Created 02/04/21 • Updated 18/03/23