useResizeObserver
A React hook that observes changes to an element's dimensions using the ResizeObserver API.
- Installation
- Add Source Code
npm install @plenty-hooks/use-resize-observer
npx @plenty-hooks/cli use-resize-observer
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
Showcase
import { useRef, useState } from 'react';
import useResizeObserver from '@plenty-hooks/use-resize-observer';
function ResizableBox() {
const ref = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
useResizeObserver(ref, (entry) => {
setSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
});
});
return (
<div>
<div
ref={ref}
style={{
resize: 'both',
overflow: 'auto',
border: '2px solid #333',
padding: '20px',
minWidth: '200px',
minHeight: '100px',
}}
>
Resize me!
</div>
<p>
Width: {Math.round(size.width)}px, Height: {Math.round(size.height)}px
</p>
</div>
);
}
Using Border Box
Track the size including padding and border:
import { useRef } from 'react';
import useResizeObserver from '@plenty-hooks/use-resize-observer';
function BorderBoxExample() {
const ref = useRef<HTMLDivElement>(null);
useResizeObserver(
ref,
(entry) => {
const borderBoxSize = entry.borderBoxSize[0];
console.log('Border box size:', {
width: borderBoxSize.inlineSize,
height: borderBoxSize.blockSize,
});
},
{ box: 'border-box' }
);
return <div ref={ref}>Content with padding and border</div>;
}
Conditional Observing
Enable or disable the observer dynamically:
import { useRef, useState } from 'react';
import useResizeObserver from '@plenty-hooks/use-resize-observer';
function ConditionalObserver() {
const ref = useRef<HTMLDivElement>(null);
const [enabled, setEnabled] = useState(true);
useResizeObserver(
ref,
(entry) => {
console.log('Size changed:', entry.contentRect);
},
{ enable: enabled }
);
return (
<div>
<button onClick={() => setEnabled(!enabled)}>
{enabled ? 'Disable' : 'Enable'} Observer
</button>
<div ref={ref}>Observed element</div>
</div>
);
}
Global Configuration
Configure default options globally for all instances:
import { configUseResizeObserver } from '@plenty-hooks/use-resize-observer';
// Configure once in your app entry point
configUseResizeObserver({
box: 'border-box',
enable: true,
});
API
useResizeObserver(ref, callback, options?)
Observes changes to an element's dimensions.
Parameters
ref: RefObject<T | null>- Ref to the element to observecallback: (entry: ResizeObserverEntry) => void- Callback fired when the element's size changesoptions(optional): Configuration object with the following properties:box?: ResizeObserverBoxOptions- The box model to observe (default:'content-box')'content-box': Size of the content area'border-box': Size including padding and border'device-pixel-content-box': Size in device pixels
enable?: boolean- If false, the observer will not be created (default:true)
Returns
void
configUseResizeObserver(options: Options)
Configures global default options for all useResizeObserver instances.
Parameters
options: Configuration object with the following properties:box?: ResizeObserverBoxOptions- The box model to observe (default:'content-box')enable?: boolean- If false, the observer will not be created (default:true)
Types
interface Options {
box?: ResizeObserverBoxOptions;
enable?: boolean;
}
type ResizeObserverBoxOptions =
| 'border-box'
| 'content-box'
| 'device-pixel-content-box';