Skip to main content

useSSR Deep Dive

The useSSR hook is a foundational utility in Archibald for detecting the current execution environment (Server vs. Client) and managing the hydration state.


Environment Detection

useSSR provides a reliable way to check if your code is currently running on the server (Node.js) or in the browser.

const { isServer, isBrowser } = useSSR();
  • isServer: true during the initial render pass on the server.
  • isBrowser: true once the code is executing in a browser environment.

Hydration State

One of the most critical features of useSSR is tracking the hydration process. Hydration is when React attaches event listeners to the static HTML sent from the server.

  • isHydrating: true after the component has mounted in the browser but before the first "client-only" render.
  • isHydrated: true after the component has successfully mounted and hydrated in the browser.

Common Use Cases

Avoiding Hydration Mismatches

If you need to render something different on the client than on the server (e.g., a timestamp or a browser-only API like window.localStorage), you must wait until the component is hydrated.

function ClientOnlyComponent() {
const { isBrowser } = useSSR();

if (!isBrowser) return null; // Don't render on server

return <div>Browser Width: {window.innerWidth}</div>;
}

Initializing Browser-only Libraries

Use isBrowser or useEffect (which only runs on the client) to initialize libraries that depend on the DOM.


How it Works Step-by-Step

Scenario: Server-Side Rendering (SSR)

  1. Server Render: React starts rendering the component tree on the server.
  2. Hook Execution: useSSR detects the absence of window and sets isServer: true, isBrowser: false.
  3. Static HTML: The component renders its "server-safe" version into a string.
  4. Transfer: The HTML is sent to the browser.

Scenario: Client-Side Hydration

  1. Initial Client Render: The browser receives the HTML and React starts the hydration process.
  2. Mount: useSSR detects the browser environment and updates isBrowser: true.
  3. Effect Trigger: An internal useEffect runs immediately after mount.
  4. State Update: The hook updates its internal state to set isHydrated: true.
  5. Re-render: The component re-renders, now allowed to show "browser-only" content without causing a hydration mismatch error.

Best Practice: Always use isBrowser or isHydrated to guard access to global browser objects like window, document, or navigator to ensure your application remains isomorphic.