react-measure is a React component that efficiently computes the dimensions and position of its child components. It leverages the browser's native `ResizeObserver` API to detect element dimension changes, offering a performant alternative to traditional polling or window resize event listeners. The library includes a polyfill for `ResizeObserver` to ensure broad browser compatibility across different environments. Currently stable at version 2.5.2, `react-measure` functions as a render prop component, allowing developers to precisely specify which rectangle properties (such as `client`, `offset`, `scroll`, `bounds`, or `margin`) are needed. Its key differentiator is the `ResizeObserver` integration, providing accurate and efficient measurement updates with minimal overhead, suitable for responsive designs and component queries. The package has been in a maintenance phase since its last major updates, providing a stable and reliable utility.
npm install react-measureVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to wrap a component with `Measure` to obtain its dimensions and apply responsive styling based on its width. It logs the measurements to the console and displays them within the component itself.
Be aware that `onResize` will fire twice on mount. You may need to debounce or conditionally handle the first call if it causes undesirable side effects, though typically the second call from `ResizeObserver` will provide the most accurate initial state.
Ensure that the direct child of the `Measure` component is always a function, receiving `{ measureRef, measure, contentRect }` as arguments.Apply `ref={measureRef}` to the root HTML element or a class component (if using `innerRef` for function components or other custom components) that you want `Measure` to observe.Wrap your component logic within a function passed as a child to `Measure`: `<Measure>{({ measureRef }) => (<div ref={measureRef}>...</div>)}</Measure>`.Ensure `measureRef` is correctly destructured from the render prop's arguments: `{({ measureRef, contentRect }) => ...}` and used within that function's scope.Carefully manage state updates within the `onResize` handler. Ensure that style changes based on measurements do not create a feedback loop that continuously triggers new resize events. Consider debouncing the `onResize` callback if you're performing heavy DOM manipulations or complex state updates.