useIsClient
The useIsClient
hook determines whether the code is being executed in a client environment (browser) or on the server. This is particularly useful for handling client-specific logic in a Server-side rendered React application.
Add the utility
npx @ivnatsr/ezreact add use-is-client
import { useSyncExternalStore } from 'react'
const emptySubscribe = () => () => {}
export function useIsClient() { return ( useSyncExternalStore( emptySubscribe, () => 'client', () => 'server' ) === 'client' )}
import { useSyncExternalStore } from 'react'
const emptySubscribe = () => () => {}
export function useIsClient() { return ( useSyncExternalStore( emptySubscribe, () => 'client', () => 'server' ) === 'client' )}
Return
This hook returns a boolean value:
true
if the code is running in a client environment (browser).false
if the code is running on the server.
Example
import { useIsClient } from './path/to/use-is-client'
const ClientOnlyExample = () => { const isClient = useIsClient()
if (!isClient) return null
return <p>Welcome to the client-side!</p>}
export default ClientOnlyExample