react-responsive is a well-established and actively maintained library (current stable version 10.0.1) that simplifies the integration of CSS media queries into React applications. It provides a declarative API for responsive design, allowing developers to render components or apply logic based on viewport characteristics. The library offers two primary interfaces: the modern `useMediaQuery` hook (introduced in v8.0.0) for functional components and a `MediaQuery` component (using render props) for class components or older patterns. Key differentiators include its support for both hooks and component-based approaches, convenient camel-cased shorthand properties for media query expressions, and a `device` prop for explicitly setting device characteristics, which is crucial for server-side rendering (SSR) and testing environments. It also ships with comprehensive TypeScript types, ensuring robust development. The library maintains a steady release cadence, focusing on stability and modern React paradigms.
npm install react-responsiveVerified import paths — ran on the pinned version, not inferred.
Demonstrates the `useMediaQuery` hook for conditional rendering based on mobile, tablet, desktop, and orientation media queries.
Upgrade to `react-responsive@8.0.0` or higher to use the `useMediaQuery` hook. Otherwise, rely on the `MediaQuery` component with a render prop.
Pass a second argument to `useMediaQuery` or `MediaQuery` component with the `device` prop to simulate client-side conditions, e.g., `useMediaQuery({ minWidth: 1224 }, { deviceWidth: 1600 })`.Only use the `device` prop when explicitly needing to override or simulate device characteristics (e.g., in SSR, testing, or specific development scenarios). Avoid using it for general client-side rendering where dynamic detection is desired.
For non-pixel units, pass the value as a string: `{ minWidth: '60em' }` instead of `{ minWidth: 960 }`.Upgrade `react-responsive` to version `8.0.0` or higher (`npm install react-responsive@latest` or `yarn add react-responsive@latest`).
When using `useMediaQuery` or `MediaQuery` in SSR, provide a second argument with a `device` object, e.g., `useMediaQuery({ minWidth: 1024 }, { deviceWidth: 1920, deviceHeight: 1080, type: 'screen' })`.Mock `window.matchMedia` in your test setup. A common mock is `window.matchMedia = jest.fn().mockImplementation(query => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), removeListener: jest.fn(), dispatchEvent: jest.fn() }));`.