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 React from 'react'
2
3import { useIsClient } from 'usehooks-ts'
4
5export default function Component() {
6 const isClient = useIsClient()
7
8 return <div>{isClient ? 'Client' : 'server'}</div>
9}

Edit on CodeSandbox

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