useIsClient()

This React Hook can be useful in a SSR environment to wait until be in a browser to execution some functions.

Indeed, in a SSR application, when the component with the useIsClient hook is mounted in the browser, its state changes and causes a re-render. It is what we want here, but, if you want a boolean, without extra render, see useSSR().

The Hook

1import { useEffect, useState } from 'react'
2
3function useIsClient() {
4 const [isClient, setClient] = useState(false)
5
6 useEffect(() => {
7 setClient(true)
8 }, [])
9
10 return isClient
11}
12
13export default useIsClient

Usage

1import { useIsClient } from 'usehooks-ts'
2
3export default function Component() {
4 const isClient = useIsClient()
5
6 return <div>{isClient ? 'Client' : 'server'}</div>
7}

Edit on CodeSandbox

See a way to make this page better?
Edit there »