The `use-ssr` package provides a lightweight React hook designed to detect the execution environment (server-side, browser, or React Native) within React components and hooks. Currently at version 1.0.25, this library offers a stable API for conditionally rendering or executing logic based on where the React application is running. It differentiates itself with zero runtime dependencies beyond React itself, comprehensive TypeScript support, and specific flags for React Native. The hook returns boolean flags (`isBrowser`, `isServer`, `isNative`) and an enum `device` string, along with capabilities like `canUseWorkers`, `canUseEventListeners`, and `canUseViewport`, making it versatile for isomorphic React applications. Its primary use case is in Universal or Server-Side Rendered (SSR) applications, such as those built with Next.js, where conditional logic based on the environment is critical for optimal performance and correct behavior.
npm install use-ssrVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to import and use the `useSSR` hook to detect the current runtime environment (browser, server, or React Native) and conditionally render UI.
Ensure `useSSR()` is called unconditionally at the top level of your functional components or custom hooks, adhering strictly to React's Rules of Hooks.
Ensure that components that depend on `useSSR` for conditional rendering produce identical HTML on both server and client for the initial render, or manage hydration carefully. For example, use `useEffect` for browser-specific side effects that shouldn't impact initial server-rendered HTML, or utilize React's `suppressHydrationWarning` for minor, intentional mismatches.
Always gate access to browser-specific APIs using the `isBrowser` flag returned by `useSSR`, or perform such access within `useEffect` hooks which only run on the client. For example, `if (isBrowser) { /* access window/document */ }` or inside `useEffect(() => { /* access window/document */ }, [isBrowser])`.Refactor your code to ensure `useSSR` is invoked only within the top level of a functional React component or a custom hook, following React's Rules of Hooks.
Wrap any code that accesses `window`, `document`, or other browser-only globals within a conditional check using `isBrowser` from `useSSR`, or within a `useEffect` hook. Example: `if (isBrowser) { window.alert('Hello'); }` or `useEffect(() => { if (isBrowser) { console.log(window.innerWidth); } }, [isBrowser]);`.Ensure `useSSR` is imported as a default export: `import useSSR from 'use-ssr';`. This package exports `useSSR` as a default, not a named export.