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
- Environment Detection: The hook checks for the presence of the
windowanddocumentobjects to determine the current execution context. - Stable State: It returns three key booleans:
isServer,isBrowser, andisClient. - 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, ordocument) 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
isBrowserbefore accessingwindow: This is a mandatory safety rule for any isomorphic code. - Use
isServerto 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 auseEffectto toggle a client-only flag after the initial mount. - Prefer
useSSRover manualtypeof windowchecks: Using the hook ensures consistent behavior across all parts of your application and makes your code more testable.