React Hook for SSR Environment Detection

1.0.25 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use the `useSSR` hook to detect the current runtime environment (browser, server, or React Native) and conditionally render UI.

import React from 'react';
import useSSR from 'use-ssr';

function App() {
  const { isBrowser, isServer, isNative, device } = useSSR();

  // This console log will show different results depending on the environment.
  // In a browser: IS BROWSER: 👍, IS SERVER: 👎, IS NATIVE: 👎, DEVICE: browser
  // On a server: IS BROWSER: 👎, IS SERVER: 👍, IS NATIVE: 👎, DEVICE: server
  console.log('IS BROWSER: ', isBrowser ? '👍' : '👎');
  console.log('IS SERVER: ', isServer ? '👍' : '👎');
  console.log('IS NATIVE: ', isNative ? '👍' : '👎');
  console.log('DEVICE: ', device);

  return (
    <div>
      <h1>Environment Detection with useSSR</h1>
      <p>Am I in a browser? {isBrowser ? 'Yes 👍' : 'No 👎'}</p>
      <p>Am I on the server? {isServer ? 'Yes 👍' : 'No 👎'}</p>
      <p>Am I in React Native? {isNative ? 'Yes 👍' : 'No 👎'}</p>
      <p>Current device type: {device}</p>
      {isBrowser && <p>This content only renders in the browser.</p>}
      {isServer && <p>This content only renders on the server.</p>}
    </div>
  );
}

// To run this in a simple SSR setup (e.g., with Next.js or a custom server rendering),
// you would integrate this App component into your server-side render function.
// For a client-side only app, you'd render it directly to the DOM.
// Example for a basic client-side render:
// import ReactDOM from 'react-dom/client';
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(<App />);
export default App;

view raw JSON →