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 React from 'react'
2
3import { useSsr } from 'usehooks-ts'
4
5export default function Component() {
6 const { isBrowser } = useSsr()
7
8 return <p>{isBrowser ? 'Browser' : 'Server'}!</p>
9}

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