useResizeObserver hook
npm install @pbr1111/use-resize-observer
!npm bundle size (scoped)
React hook implementation of ResizeObserver to measure the size of an element.
- Features
- Installation
- Usage
- useResizeObserver
- useDebounceResizeObserver
- useThrottleResizeObserver
- Uses RefCallback to react to nodes that change their reference (like conditional nodes).
- Provides useDebounceResizeObserver and useThrottleResizeObserver hooks for an optimized debouncing and throttling exprience, avoiding unnecessary rerenders.
- Written in TypeScript. The declaration files (.d.ts) are included in the package.
With yarn:
``sh`
yarn add @pbr1111/use-resize-observer
With npm:
`sh`
npm install @pbr1111/use-resize-observer
All hooks return the same object:
| Property | Description |
| -------- | --------------------------------------------------------------------------------- |
| ref | RefCallback ref to be observed |width
| | Element width. It will be undefined until the size of the element is calculated. |height
| | Element height. It will be undefined until the size of the element is calculated. |
This hook has no input parameters.
`tsx
import React from 'react';
import { useResizeObserver } from '@pbr1111/use-resize-observer';
const App = () => {
const { ref, width, height } = useResizeObserver
return (
useDebounceResizeObserver
$3
| Parameter | Required | Description |
| --------- | -------- | --------------------------- |
|
delayMs | Yes | Delay time in milliseconds. |$3
`tsx
import React from 'react';
import { useDebounceResizeObserver } from '@pbr1111/use-resize-observer';const App = () => {
const { ref, width, height } = useDebounceResizeObserver(
500
);
return (
Width: {width}px
Height: {height}px
);
};
`useThrottleResizeObserver
$3
| Parameter | Required | Description |
| --------- | -------- | --------------------------- |
|
delayMs | Yes | Delay time in milliseconds. |$3
`tsx
import React from 'react';
import { useThrottleResizeObserver } from '@pbr1111/use-resize-observer';const App = () => {
const { ref, width, height } = useThrottleResizeObserver(
500
);
return (
Width: {width}px
Height: {height}px
);
};
``