use Mounted (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}
</>
)
}