Skip to main content

useSSR: Handling Server-Side vs Client-Side Environments

Best Practices Guide for Isomorphic Development


Introduction

Archibald is an isomorphic framework, meaning your components run on both the server (Node.js) and the client (the browser). The useSSR hook provides a standardized way to detect the current environment and adjust your component's behavior accordingly.

How it works

  1. Environment Detection: The hook checks for the presence of the window and document objects to determine the current execution context.
  2. Stable State: It returns three key booleans: isServer, isBrowser, and isClient.
  3. Hydration Support: It helps ensure that components behave correctly during the critical hydration phase, where React transitions from a server-rendered HTML string to a fully interactive client-side application.

Why use useSSR?

  • Prevent Reference Errors: Safely avoid accessing browser-only APIs (like window, localStorage, or document) during the server-side rendering pass.
  • Conditional Rendering: Render different components (or no component at all) on the server to optimize the initial HTML payload.
  • Hydration Safety: Minimize "hydration mismatch" warnings by ensuring the server and client initial render outputs are identical where necessary.

See Also

For a detailed technical breakdown and additional implementation patterns, refer to the following resources:


Key Takeaways

  • Always check isBrowser before accessing window: This is a mandatory safety rule for any isomorphic code.
  • Use isServer to skip expensive browser-only initialization: Avoid running setup logic that only makes sense in a browser environment.
  • Be careful with conditional rendering: If you render different content on the server (isServer) vs the client (isBrowser), React may warn about hydration mismatches. For these cases, consider using a useEffect to toggle a client-only flag after the initial mount.
  • Prefer useSSR over manual typeof window checks: Using the hook ensures consistent behavior across all parts of your application and makes your code more testable.