### Install react-resize-detector Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Install the library using npm, yarn, or pnpm. This is the first step before using the hook in your React application. ```bash npm install react-resize-detector # OR yarn add react-resize-detector # OR pnpm add react-resize-detector ``` -------------------------------- ### Basic Usage Example Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Demonstrates the simplest way to use the `useResizeDetector` hook to display the dimensions of a div element. ```APIDOC ## Basic Usage ```tsx import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () => { const { width, height, ref } = useResizeDetector(); return
{`${width}x${height}`}
; }; ``` ### Description This example shows how to integrate `useResizeDetector` into a functional component. The `ref` returned by the hook is attached to a `div` element, and its dimensions (`width` and `height`) are displayed within that same `div`. The dimensions will update automatically as the element is resized. ``` -------------------------------- ### CSS Container Queries Example Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Demonstrates how to use CSS Container Queries to apply styles based on container size. This is a pure CSS alternative for responsive design. ```html

Card title

Card content

``` ```css .post { container-type: inline-size; } /* Default heading styles for the card title */ .card h2 { font-size: 1em; } /* If the container is larger than 700px */ @container (min-width: 700px) { .card h2 { font-size: 2em; } } ``` -------------------------------- ### Advanced Usage with External Ref Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md An advanced example demonstrating the use of an external ref with `useResizeDetector`. This approach is not recommended due to potential unexpected behavior during dynamic mounting and unmounting. ```tsx import { useRef } from 'react'; import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () => { const targetRef = useRef(null); const { width, height } = useResizeDetector({ targetRef }); return
{`${width}x${height}`}
; }; ``` -------------------------------- ### useResizeDetector with Resize Callback Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md This example shows how to provide an `onResize` callback to the `useResizeDetector` hook. The callback receives an object with width and height, or null if the element is unmounted. ```tsx import { useCallback } from 'react'; import { useResizeDetector, OnResizeCallback } from 'react-resize-detector'; const CustomComponent = () => { const onResize: OnResizeCallback = useCallback((payload) => { if (payload.width !== null && payload.height !== null) { console.log('Dimensions:', payload.width, payload.height); } else { console.log('Element unmounted'); } }, []); const { width, height, ref } = useResizeDetector({ onResize, }); return
{`${width}x${height}`}
; }; ``` -------------------------------- ### Chart Resizing with react-resize-detector and Debounce Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md This example demonstrates how to resize a chart component. It uses the 'debounce' refresh mode with a rate of 100ms and redraws the chart when dimensions change. ```jsx import { useResizeDetector } from 'react-resize-detector'; import { useEffect, useRef } from 'react'; const Chart = () => { const chartRef = useRef(null); const { width, height, ref } = useResizeDetector({ refreshMode: 'debounce', refreshRate: 100, }); useEffect(() => { if (width && height && chartRef.current) { // Redraw chart with new dimensions redrawChart(chartRef.current, width, height); } }, [width, height]); return ; }; ``` -------------------------------- ### Get Resize Detector Return Values Source: https://context7.com/maslianok/react-resize-detector/llms.txt Understand the structure of the object returned by `useResizeDetector`. Width and height are undefined before the first measurement and after unmount. ```typescript import type { UseResizeDetectorReturn } from 'react-resize-detector'; // Destructure freely — all fields are always present const { ref, width, height }: UseResizeDetectorReturn = useResizeDetector(); // `ref` is a callback-ref proxy compatible with React's ref prop: // ref(node) — called by React when element mounts/unmounts // ref.current — readable, returns the currently observed element ``` -------------------------------- ### Observing Only One Dimension (Width or Height) Source: https://context7.com/maslianok/react-resize-detector/llms.txt Configure the hook to only track and trigger re-renders for specific dimensions by setting 'handleWidth' and 'handleHeight' to true or false. This example observes only the width. ```tsx import { useResizeDetector } from 'react-resize-detector'; const WidthOnlyComponent = () => { const { width, ref } = useResizeDetector({ handleWidth: true, handleHeight: false, // no re-render on height change }); return
Width: {width}px
; }; ``` -------------------------------- ### Basic Usage of useResizeDetector Hook Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md A simple example of using the `useResizeDetector` hook to get the width and height of a div. The hook returns a ref that should be attached to the observed element. ```tsx import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () => { const { width, height, ref } = useResizeDetector(); return
{`${width}x${height}`}
; }; ``` -------------------------------- ### Patch Resize Callback with Debounce/Throttle Source: https://context7.com/maslianok/react-resize-detector/llms.txt Use `patchResizeCallback` to wrap a `ResizeObserverCallback` with debounce or throttle. This utility is exported for advanced use cases or custom observer setups. ```typescript import { patchResizeCallback } from 'react-resize-detector/src/utils'; // (exported from internal utils — primarily for testing or custom observer setups) const rawCallback: ResizeObserverCallback = (entries) => { entries.forEach(entry => console.log(entry.contentRect)); }; // Returns a debounced version of the callback const debouncedCallback = patchResizeCallback(rawCallback, 'debounce', 300, { trailing: true }); // Returns a throttled version of the callback const throttledCallback = patchResizeCallback(rawCallback, 'throttle', 100, { leading: true }); // Returns the original callback unchanged when mode is undefined const noopCallback = patchResizeCallback(rawCallback, undefined, 1000, undefined); // Use with a raw ResizeObserver const observer = new ResizeObserver(debouncedCallback); observer.observe(document.getElementById('target')!); ``` -------------------------------- ### Customizing Box Model for Observation Source: https://context7.com/maslianok/react-resize-detector/llms.txt Use 'observerOptions.box' to specify which CSS box model to measure ('content-box', 'border-box'). The default ('undefined') measures the inner content box. This example includes padding and border. ```tsx import { useResizeDetector } from 'react-resize-detector'; const BorderBoxComponent = () => { const { width, height, ref } = useResizeDetector({ observerOptions: { box: 'border-box' }, }); return (
Including padding+border: {width}×{height}
); }; ``` -------------------------------- ### Mock ResizeObserver for Tests Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Sets up a mock for the ResizeObserver API before each test and restores the original after each test. This is crucial for reliable testing of components that depend on ResizeObserver. ```jsx const { ResizeObserver } = window; beforeEach(() => { delete window.ResizeObserver; // Mock ResizeObserver for tests window.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })); }); afterEach(() => { window.ResizeObserver = ResizeObserver; jest.restoreAllMocks(); }); ``` -------------------------------- ### Mock ResizeObserver for Testing Source: https://context7.com/maslianok/react-resize-detector/llms.txt Set up mocks for `ResizeObserver` in Jest/Vitest environments where it's not natively implemented. This allows manual triggering of resize events in tests. ```typescript // jest.setup.ts or vitest.setup.ts const { ResizeObserver } = window; beforeEach(() => { // Remove native (undefined in jsdom) and install mock delete (window as any).ResizeObserver; window.ResizeObserver = jest.fn().mockImplementation((callback) => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), // Optionally expose callback to trigger manually in tests: __callback: callback, })); }); afterEach(() => { window.ResizeObserver = ResizeObserver; jest.restoreAllMocks(); }); // In a test — trigger a resize manually: it('updates width on resize', () => { const { getByTestId } = render(); const instance = (window.ResizeObserver as jest.Mock).mock.results[0].value; act(() => { instance.__callback([ { contentRect: { width: 400, height: 300 }, borderBoxSize: [], contentBoxSize: [] }, ]); }); expect(getByTestId('width').textContent).toBe('400'); }); ``` -------------------------------- ### Performance Optimization with react-resize-detector Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Optimize performance by selectively tracking only width changes, using debounce for rapid updates, and skipping the initial mount calculation. It also configures the observer to use 'border-box'. ```jsx import { useResizeDetector } from 'react-resize-detector'; const OptimizedComponent = () => { const { width, height, ref } = useResizeDetector({ // Only track width changes handleHeight: false, // Debounce rapid changes refreshMode: 'debounce', refreshRate: 150, // Skip initial mount calculation skipOnMount: true, // Use border-box for more accurate measurements observerOptions: { box: 'border-box' }, }); return
Optimized: {width}px wide
; }; ``` -------------------------------- ### Usage with Resize Callback Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Shows how to provide a callback function to `useResizeDetector` to perform actions when the element's size changes. ```APIDOC ## With Resize Callback ```tsx import { useCallback } from 'react'; import { useResizeDetector, OnResizeCallback } from 'react-resize-detector'; const CustomComponent = () => { const onResize: OnResizeCallback = useCallback((payload) => { if (payload.width !== null && payload.height !== null) { console.log('Dimensions:', payload.width, payload.height); } else { console.log('Element unmounted'); } }, []); const { width, height, ref } = useResizeDetector({ onResize, }); return
{`${width}x${height}`}
; }; ``` ### Description This example demonstrates how to use the `onResize` callback prop. The `onResize` function is executed whenever the observed element's dimensions change. It receives a `payload` object containing the new `width` and `height`. This is useful for triggering side effects or complex logic based on element size. ``` -------------------------------- ### Responsive Component with react-resize-detector Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Use this snippet to create components that adapt their styling based on their current dimensions. It dynamically adjusts padding, font size, and flex direction. ```jsx import { useResizeDetector } from 'react-resize-detector'; const ResponsiveCard = () => { const { width, ref } = useResizeDetector(); const cardStyle = { padding: width > 600 ? '2rem' : '1rem', fontSize: width > 400 ? '1.2em' : '1em', flexDirection: width > 500 ? 'row' : 'column', }; return (

Responsive Card

Width: {width}px

); }; ``` -------------------------------- ### Advanced Usage with External Ref Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Illustrates how to use `useResizeDetector` with an externally managed ref, though this approach is generally not recommended. ```APIDOC ## With External Ref (Advanced) _It's not advised to use this approach, as dynamically mounting and unmounting the observed element could lead to unexpected behavior._ ```tsx import { useRef } from 'react'; import { useResizeDetector } from 'react-resize-detector'; const CustomComponent = () => { const targetRef = useRef(null); const { width, height } = useResizeDetector({ targetRef }); return
{`${width}x${height}`}
; }; ``` ### Description This advanced example shows how to pass an existing `useRef` to `useResizeDetector` via the `targetRef` prop. This allows you to observe an element that is managed by another part of your component or a parent component. However, be cautious, as direct manipulation of the observed element outside of the hook's management can lead to unpredictable results. ``` -------------------------------- ### Skipping Initial Resize Event on Mount Source: https://context7.com/maslianok/react-resize-detector/llms.txt Use 'skipOnMount: true' to prevent the onResize callback from firing immediately after the component mounts. This is helpful if you only want to react to subsequent size changes. ```tsx import { useResizeDetector } from 'react-resize-detector'; const SkipMountComponent = () => { const { width, height, ref } = useResizeDetector({ skipOnMount: true, }); return
{width ?? 'not yet measured'}×{height ?? '—'}
; }; ``` -------------------------------- ### useResizeDetectorProps Configuration Source: https://context7.com/maslianok/react-resize-detector/llms.txt Interface for all options accepted by the `useResizeDetector` hook. All properties are optional. ```APIDOC ## `useResizeDetectorProps` — Hook configuration interface Full TypeScript interface for all options accepted by `useResizeDetector`. Every property is optional. ```typescript import type { useResizeDetectorProps, OnResizeCallback } from 'react-resize-detector'; const config: useResizeDetectorProps = { // Fired on every resize (or when element unmounts with null values) onResize: (payload) => { if (payload.width !== null) { console.log(payload.width, payload.height, payload.entry); } }, handleWidth: true, // watch width changes (default: true) handleHeight: true, // watch height changes (default: true) skipOnMount: false, // suppress first event on mount (default: false) disableRerender: false, // callback-only, no state updates (default: false) refreshMode: 'debounce', // 'throttle' | 'debounce' | undefined refreshRate: 150, // ms interval/delay (default: 1000) refreshOptions: { leading: false, trailing: true }, observerOptions: { box: 'border-box', // 'content-box' | 'border-box' | undefined }, // External ref — prefer the returned ref callback instead // targetRef: myRef, }; ``` ``` -------------------------------- ### Handle Resize Payload Source: https://context7.com/maslianok/react-resize-detector/llms.txt Process the `ResizePayload` delivered to the `onResize` callback. When the element is mounted, it carries real dimensions; when it unmounts, all values are `null`. ```typescript import type { ResizePayload, OnResizeCallback } from 'react-resize-detector'; const handler: OnResizeCallback = (payload: ResizePayload) => { if (payload.width !== null) { // Mounted branch — safe to use all fields const { width, height, entry } = payload; console.log('content rect:', entry.contentRect); console.log('border-box:', entry.borderBoxSize[0]?.inlineSize); console.log('content-box:', entry.contentBoxSize[0]?.inlineSize); } else { // Unmounted branch — width, height and entry are all null console.log('element removed from DOM'); } }; ``` -------------------------------- ### ResizePayload Structure Source: https://context7.com/maslianok/react-resize-detector/llms.txt Discriminated union passed to the `onResize` callback. When the element is mounted it carries real dimensions; when it unmounts all values are `null`. ```APIDOC ## `ResizePayload` — Payload delivered to `onResize` Discriminated union passed to the `onResize` callback. When the element is mounted it carries real dimensions; when it unmounts all values are `null`. ```typescript import type { ResizePayload, OnResizeCallback } from 'react-resize-detector'; const handler: OnResizeCallback = (payload: ResizePayload) => { if (payload.width !== null) { // Mounted branch — safe to use all fields const { width, height, entry } = payload; console.log('content rect:', entry.contentRect); console.log('border-box:', entry.borderBoxSize[0]?.inlineSize); console.log('content-box:', entry.contentBoxSize[0]?.inlineSize); } else { // Unmounted branch — width, height and entry are all null console.log('element removed from DOM'); } }; ``` ``` -------------------------------- ### Throttling and Debouncing Resize Events Source: https://context7.com/maslianok/react-resize-detector/llms.txt Control the frequency of resize updates using 'refreshMode' ('throttle' or 'debounce') and 'refreshRate'. 'refreshOptions' allow further customization of event firing (leading/trailing edge). ```tsx import { useResizeDetector } from 'react-resize-detector'; const ThrottledComponent = () => { const { width, height, ref } = useResizeDetector({ refreshMode: 'throttle', // 'throttle' | 'debounce' refreshRate: 200, // milliseconds (default: 1000) refreshOptions: { leading: true, // fire on the leading edge trailing: true, // fire on the trailing edge }, }); return
{width}×{height}
; }; ``` -------------------------------- ### patchResizeCallback Utility Source: https://context7.com/maslianok/react-resize-detector/llms.txt Internal throttle/debounce wrapper for `ResizeObserverCallback`. Used internally by `useResizeDetector` but exported for advanced use cases. ```APIDOC ## `patchResizeCallback` — Internal throttle/debounce wrapper (utility) Wraps a `ResizeObserverCallback` with `es-toolkit` debounce or throttle based on the given `refreshMode`. Used internally by `useResizeDetector` but exported for advanced use cases. ```typescript import { patchResizeCallback } from 'react-resize-detector/src/utils'; // (exported from internal utils — primarily for testing or custom observer setups) const rawCallback: ResizeObserverCallback = (entries) => { entries.forEach(entry => console.log(entry.contentRect)); }; // Returns a debounced version of the callback const debouncedCallback = patchResizeCallback(rawCallback, 'debounce', 300, { trailing: true }); // Returns a throttled version of the callback const throttledCallback = patchResizeCallback(rawCallback, 'throttle', 100, { leading: true }); // Returns the original callback unchanged when mode is undefined const noopCallback = patchResizeCallback(rawCallback, undefined, 1000, undefined); // Use with a raw ResizeObserver const observer = new ResizeObserver(debouncedCallback); observer.observe(document.getElementById('target')!); ``` ``` -------------------------------- ### Configure useResizeDetector Hook Source: https://context7.com/maslianok/react-resize-detector/llms.txt Configure the `useResizeDetector` hook with various options like resize callbacks, dimension handling, refresh modes, and observer options. All properties are optional. ```typescript import type { useResizeDetectorProps, OnResizeCallback } from 'react-resize-detector'; const config: useResizeDetectorProps = { // Fired on every resize (or when element unmounts with null values) onResize: (payload) => { if (payload.width !== null) { console.log(payload.width, payload.height, payload.entry); } }, handleWidth: true, // watch width changes (default: true) handleHeight: true, // watch height changes (default: true) skipOnMount: false, // suppress first event on mount (default: false) disableRerender: false, // callback-only, state updates (default: false) refreshMode: 'debounce', // 'throttle' | 'debounce' | undefined refreshRate: 150, // ms interval/delay (default: 1000) refreshOptions: { leading: false, trailing: true }, observerOptions: { box: 'border-box', // 'content-box' | 'border-box' | undefined }, // External ref — prefer the returned ref callback instead // targetRef: myRef, }; ``` -------------------------------- ### Minimal useResizeDetector Usage Source: https://context7.com/maslianok/react-resize-detector/llms.txt Basic implementation of the hook. Attach the returned ref to an element to observe its dimensions. The component re-renders when width or height changes. ```tsx import { useResizeDetector } from 'react-resize-detector'; const MinimalComponent = () => { const { width, height, ref } = useResizeDetector(); return (
{width}×{height}
); }; ``` -------------------------------- ### Using useResizeDetector with an External Ref Source: https://context7.com/maslianok/react-resize-detector/llms.txt Attach the hook to an existing ref (e.g., forwarded from a parent component) using the 'targetRef' option. Be cautious with dynamic mounting/unmounting as it may lead to unexpected behavior. ```tsx import { useRef } from 'react'; import { useResizeDetector } from 'react-resize-detector'; const ExternalRefComponent = () => { const targetRef = useRef(null); const { width, height } = useResizeDetector({ targetRef }); return
{width}×{height}
; }; ``` -------------------------------- ### useResizeDetector with onResize Callback Source: https://context7.com/maslianok/react-resize-detector/llms.txt Utilize the onResize callback to perform side effects when dimensions change, without necessarily causing a component re-render. The callback receives an object with width, height, and the ResizeObserverEntry. It signals 'element removed' when the observed element unmounts. ```tsx import { useCallback } from 'react'; import { useResizeDetector } from 'react-resize-detector'; import type { OnResizeCallback } from 'react-resize-detector'; const WithCallback = () => { const onResize: OnResizeCallback = useCallback((payload) => { if (payload.width !== null && payload.height !== null) { // Element is mounted — payload also contains the raw ResizeObserverEntry console.log('new size', payload.width, payload.height, payload.entry); } else { // Element was unmounted; width/height/entry are null console.log('element removed'); } }, []); const { ref } = useResizeDetector({ onResize }); return
Resize me
; }; ``` -------------------------------- ### UseResizeDetectorReturn Value Source: https://context7.com/maslianok/react-resize-detector/llms.txt Interface for the object returned by the `useResizeDetector` hook. `width` and `height` are `undefined` before the first measurement and after unmount. ```APIDOC ## `UseResizeDetectorReturn` — Hook return value interface Shape of the object returned by `useResizeDetector`. `width` and `height` are `undefined` before the first measurement and after unmount. ```typescript import type { UseResizeDetectorReturn } from 'react-resize-detector'; // Destructure freely — all fields are always present const { ref, width, height }: UseResizeDetectorReturn = useResizeDetector(); // `ref` is a callback-ref proxy compatible with React's ref prop: // ref(node) — called by React when element mounts/unmounts // ref.current — readable, returns the currently observed element ``` ``` -------------------------------- ### Conditional Rendering with useResizeDetector Source: https://context7.com/maslianok/react-resize-detector/llms.txt The hook automatically manages the ResizeObserver when the target element is conditionally rendered. The observer disconnects and reconnects as the element mounts and unmounts. ```tsx import { useResizeDetector } from 'react-resize-detector'; const ConditionalComponent = ({ show }: { show: boolean }) => { const { width, height, ref } = useResizeDetector(); // When `show` toggles, the observer disconnects/reconnects automatically. return show ? (
{width}×{height}
) : null; }; ``` -------------------------------- ### useResizeDetector Hook Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md The primary hook provided by the library. It accepts an optional props object and returns an object containing the observed element's width, height, and a ref to attach to the target element. ```APIDOC ## Hook Signature ```typescript useResizeDetector( props?: useResizeDetectorProps ): UseResizeDetectorReturn ``` ### Description This hook is the main interface for detecting element resize events. It returns the current width and height of the observed element, along with a ref that should be attached to the target DOM element. ### Parameters - **props** (useResizeDetectorProps) - Optional. An object containing configuration options for the hook. - **targetRef** (RefObject) - Optional. An external ref to the target element. If not provided, the hook will create and manage its own ref. - **onResize** (OnResizeCallback) - Optional. A callback function that is invoked whenever the observed element's dimensions change. It receives a payload object with `width` and `height`. - **skipOnMount** (boolean) - Optional. If true, the `onResize` callback will not be called on the initial mount. - **refreshMode** (string) - Optional. Specifies how often to refresh the dimensions. Possible values: 'throttle', 'debounce', 'none'. Defaults to 'throttle'. - **refreshOptions** (object) - Optional. Options for throttling or debouncing the refresh mode. ### Return Value - **width** (number | null) - The current width of the observed element, or null if not yet measured or unmounted. - **height** (number | null) - The current height of the observed element, or null if not yet measured or unmounted. - **ref** (RefObject) - A ref object that should be attached to the target DOM element to be observed. ``` -------------------------------- ### Disable Re-renders with react-resize-detector Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md Prevent component re-renders on resize by setting `disableRerender` to `true`. Resize events are then handled exclusively through the `onResize` callback, allowing external state updates without re-rendering. ```jsx import { useResizeDetector } from 'react-resize-detector'; const NonRerenderingComponent = () => { const { ref } = useResizeDetector({ // Disable re-renders triggered by the hook disableRerender: true, // Handle resize events through callback only onResize: ({ width, height }) => { // Update external state or perform side effects // without causing component re-renders console.log('Resized to:', width, height); }, }); return
This component won't re-render on resize
; }; ``` -------------------------------- ### useResizeDetector Hook Signature Source: https://github.com/maslianok/react-resize-detector/blob/master/README.md The TypeScript signature for the `useResizeDetector` hook, showing its generic type parameter for the observed element and its optional props and return type. ```typescript useResizeDetector( props?: useResizeDetectorProps ): UseResizeDetectorReturn ``` -------------------------------- ### Disabling Component Re-renders on Resize Source: https://context7.com/maslianok/react-resize-detector/llms.txt Set 'disableRerender' to true to prevent the component from re-rendering when dimensions change. This is useful for triggering side effects only, such as updating document title, via the onResize callback. ```tsx import { useResizeDetector } from 'react-resize-detector'; const NoRerenderComponent = () => { const { ref } = useResizeDetector({ disableRerender: true, onResize: ({ width, height }) => { // Side effects only — component never re-renders due to resize document.title = `${width}×${height}`; }, }); return
This component never re-renders on resize
; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.