useIsClient()

This react hook is very simple but it is useful. Indeed, if you manually do a typeof window! ==" undefined " type check, then your function will be escaped, but it will stop there.

Thanks to this hook, there will be a first render where isClient will be false, then when the window is ready, the useEffect will be executed, will update the value of isClient and restart your component with the window defined.

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 './useIsClient'
4
5export default function Component() {
6 const isClient = useIsClient()
7
8 return <div>{isClient ? 'Client' : 'server'}</div>
9}

Created:
8 months ago