useSsr()

Quickly know where your code will be executed;

  • In the server (Server-Side-Rendering) or
  • In the client, the navigator

This hook doesn't cause an extra render, it just returns the value directly, at the mount time, and it didn't re-trigger if the value changes.

Otherwise, If you want to be notified when the value changes to react to it, you can use useIsClient() instead.

The Hook

1function useSsr() {
2 const isDOM =
3 typeof window !== 'undefined' &&
4 window.document &&
5 window.document.documentElement
6
7 return {
8 isBrowser: isDOM,
9 isServer: !isDOM,
10 }
11}
12
13export default useSsr

Usage

1import { useSsr } from 'usehooks-ts'
2
3export default function Component() {
4 const { isBrowser } = useSsr()
5
6 return <p>{isBrowser ? 'Browser' : 'Server'}!</p>
7}

Edit on CodeSandbox

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