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.documentElement67 return {8 isBrowser: isDOM,9 isServer: !isDOM,10 }11}1213export default useSsr
Usage
1import { useSsr } from 'usehooks-ts'23export default function Component() {4 const { isBrowser } = useSsr()56 return <p>{isBrowser ? 'Browser' : 'Server'}!</p>7}
See a way to make this page better?
Edit there »