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:trueduring the initial render pass on the server.isBrowser:trueonce 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:trueafter the component has mounted in the browser but before the first "client-only" render.isHydrated:trueafter 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)
- Server Render: React starts rendering the component tree on the server.
- Hook Execution:
useSSRdetects the absence ofwindowand setsisServer: true,isBrowser: false. - Static HTML: The component renders its "server-safe" version into a string.
- Transfer: The HTML is sent to the browser.
Scenario: Client-Side Hydration
- Initial Client Render: The browser receives the HTML and React starts the hydration process.
- Mount:
useSSRdetects the browser environment and updatesisBrowser: true. - Effect Trigger: An internal
useEffectruns immediately after mount. - State Update: The hook updates its internal state to set
isHydrated: true. - 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.