react-resize-aware and react-resize-detector are both React libraries designed to detect changes in an element's dimensions. react-resize-aware typically employs a Render Prop pattern or Higher-Order Component (HOC) to inject size data, often relying on iframe-based detection or ResizeObserver polyfills for older browser support. react-resize-detector offers a more modern approach, frequently providing a dedicated React Component, Hooks, and HOCs, with a strong focus on leveraging the native ResizeObserver API for performance while maintaining fallbacks. Both solve the problem of responding to container size changes without direct access to the window resize event.
When building responsive React components, listening to the window resize event isn't enough. You often need to know when a specific div, sidebar, or chart container changes size. react-resize-aware and react-resize-detector both solve this, but they take different architectural approaches to detecting and delivering size data.
react-resize-aware traditionally leans on the Higher-Order Component (HOC) pattern or Render Props.
width and height props.// react-resize-aware: HOC Pattern
import { withResizeDetector } from 'react-resize-aware';
const MyComponent = ({ width, height }) => (
<div>{width} x {height}</div>
);
export default withResizeDetector(MyComponent);
react-resize-detector supports modern Hooks, Components, and HOCs.
useResizeDetector hook for functional components.<ResizeDetector> component for declarative usage.// react-resize-detector: Hook Pattern
import { useResizeDetector } from 'react-resize-detector';
const MyComponent = () => {
const { ref, width, height } = useResizeDetector();
return (
<div ref={ref}>
{width} x {height}
</div>
);
};
react-resize-aware often relies on an iframe-based detection strategy or older polyfills.
// react-resize-aware: Implicit iframe injection
// The library handles the DOM manipulation internally
<ResizeAware>
{({ width, height }) => <div>{width} x {height}</div>}
</ResizeAware>
react-resize-detector prioritizes the native ResizeObserver API.
// react-resize-detector: Native ResizeObserver usage
// Handled internally by the hook/component
const { ref } = useResizeDetector();
// The 'ref' attaches the observer directly to the DOM node
<div ref={ref}>Content</div>
react-resize-aware typically passes size data directly as props to the wrapped component.
this.props.width or function arguments.// react-resize-aware: Data via Props
const Chart = ({ width, height }) => {
useEffect(() => {
// Logic runs on render when props change
drawChart(width, height);
}, [width, height]);
return <canvas />;
};
react-resize-detector allows direct callback handlers alongside data exposure.
onResize function to trigger side effects immediately.// react-resize-detector: Callback Handler
const { ref } = useResizeDetector({
onResize: (width, height) => {
// Logic runs immediately on resize, before re-render
console.log('Resized:', width, height);
}
});
return <div ref={ref}>Content</div>;
react-resize-aware may require manual throttling in some implementations.
lodash.throttle to prevent lag.// react-resize-aware: Manual Throttling often needed
const ThrottledComponent = ({ width, height }) => {
const debouncedWidth = useDebounce(width, 300);
return <div>{debouncedWidth}</div>;
};
react-resize-detector includes built-in throttling and debouncing options.
refreshRate directly in the hook or component props.// react-resize-detector: Built-in Throttling
const { ref } = useResizeDetector({
refreshRate: 500 // Limits updates to every 500ms
});
return <div ref={ref}>Optimized Content</div>;
Despite their differences, both libraries aim to solve the same core problem with overlapping features.
// Both libraries provide similar data shape
// { width: number, height: number }
const { width, height } = useResizeDetector(); // or via props
// Both can wrap a child component
<ResizeDetector>
<ThirdPartyChart />
</ResizeDetector>
window during initial server render.// Both check for window existence internally
if (typeof window !== 'undefined') {
// Initialize observer
}
// Both support typed generics
interface Props { width: number; height: number; }
| Feature | Shared by Both |
|---|---|
| Core Data | π Width & Height |
| Integration | π§© Component Wrapping |
| Environment | π SSR Compatible |
| Typing | β TypeScript Definitions |
| Goal | π― Element Resize Detection |
| Feature | react-resize-aware | react-resize-detector |
|---|---|---|
| Primary API | ποΈ HOC / Render Props | βοΈ Hooks / Component |
| Engine | πΌοΈ Iframe / Polyfill | ποΈ ResizeObserver (Native) |
| Throttling | βοΈ Manual (often) | π Built-in Configuration |
| Callbacks | π₯ Via Props | π Direct onResize Handler |
| Modernization | π°οΈ Legacy Patterns | π Modern React Patterns |
react-resize-aware is like a reliable older tool π¨βit gets the job done and is stable for legacy systems. It is best suited for maintaining existing applications where migrating to Hooks would be too costly. However, for new development, its patterns feel dated.
react-resize-detector is like a modern power drill πͺβit leverages native browser capabilities and modern React features. It is the stronger choice for new projects, offering better performance via ResizeObserver and a cleaner API with Hooks.
Final Thought: While both detect resizes, react-resize-detector aligns better with the future of React development. Unless you are locked into a legacy stack, the modern API and performance benefits make it the preferred architectural choice.
Choose react-resize-aware if you are maintaining a legacy codebase that already depends on its specific HOC or Render Prop patterns and requires consistent behavior across very old browsers without polyfill configuration. It is a stable, minimal solution for projects that prioritize simplicity over modern API features. However, be aware that it may lack the active feature updates found in newer alternatives.
Choose react-resize-detector if you are starting a new project or want to leverage modern React patterns like Hooks (useResizeDetector). It provides better performance through native ResizeObserver usage and offers flexible integration options including a standalone component, HOC, and hook. This package is generally more active and aligns better with current React best practices for state management and side effects.
It does one thing, it does it well: listens to resize events on any HTML element.
react-resize-aware is a zero dependency, ~600 bytes React Hook you can use to detect resize events without relying on intervals, loops, DOM manipulation detection or CSS redraws.
It takes advantage of the resize event on the HTMLObjectElement, works on any browser I know of, and it's super lightweight.
In addition, it doesn't directly alters the DOM, everything is handled by React.
Looking for the 2.0 docs? Click here
yarn add react-resize-aware
or with npm:
npm install --save react-resize-aware
The API is simple yet powerful, the useResizeAware Hook
returns a React node you will place inside the measured element, and an object containing its sizes:
import React from "react";
import useResizeAware from "react-resize-aware";
const App = () => {
const [resizeListener, sizes] = useResizeAware();
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here. (div sizes are {sizes?.width} x {sizes?.height})
</div>
);
};
Heads up!: Make sure to assign a
position != initialto the HTMLElement you want to target (relative,absolute, orfixedwill work).
The Hook returns an array with two elements inside:
[resizeListener, ...] (first element)This is an invisible React node that must be placed as direct-child of the HTMLElement you want to listen the resize events of.
The node is not going to interfer with your layouts, I promise.
[..., sizes] (second element)This object contains the width and height properties, it could be null if the element is not yet rendered.
reporterYou can customize the properties of the sizes object by passing a custom reporter function as first argument of useResizeAware.
const customReporter = (target: ?HTMLIFrameElement) => ({
clientWidth: target != null ? target.clientWidth : 0,
});
const [resizeListener, sizes] = useResizeAware(customReporter);
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here. (div clientWidth is {sizes.clientWidth})
</div>
);
The above example will report the clientWidth rather than the default offsetWidth and offsetHeight.
For completeness, below you can find an example to show how to make your code react to size variations using React Hooks:
const App = () => {
const [resizeListener, sizes] = useResizeAware();
React.useEffect(() => {
console.log("Do something with the new size values");
}, [sizes.width, sizes.height]);
return (
<div style={{ position: "relative" }}>
{resizeListener}
Your content here.
</div>
);
};