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
}

Usage

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