Skip to content

useResizeObserver ​

Hook that gives you resize observer state

browser
test coverage
Last changed: yesterday

TIP

This hook uses ResizeObserver browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation ​

Library
CLI
Manual
typescript
import { useResizeObserver } from '@siberiacancode/reactuse';

Usage ​

typescript
const { ref, entries } = useResizeObserver();
// or
const { entries } = useResizeObserver(ref);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
options.enabled?booleantrueThe IntersectionObserver options
options.box?boolean-The IntersectionObserver options
options.onChange?(entries: ResizeObserverEntry[], observer: ResizeObserver) => void-The callback to execute when resize is detected

Returns

UseResizeObserverReturn & { ref: StateRef<Target> }

Parameters

NameTypeDefaultNote
targetHookTarget-The target element to observe
options.enabled?booleantrueThe IntersectionObserver options
options.box?boolean-The IntersectionObserver options
options.onChange?(entries: ResizeObserverEntry[], observer: ResizeObserver) => void-The callback to execute when resize is detected

Returns

UseResizeObserverReturn

Type declaration ​

typescript
import type { HookTarget } from '@/utils/helpers';

import type { StateRef } from '../useRefState/useRefState';

export interface UseResizeObserverOptions extends ResizeObserverOptions {
  /** The enabled state */
  enabled?: boolean;
  /** The resize observer callback */
  onChange?: (entries: ResizeObserverEntry[], observer: ResizeObserver) => void;
}

export interface UseResizeObserverReturn {
  /** The resize observer entries */
  entries: ResizeObserverEntry[];
}

export interface UseResizeObserver {
  (target: HookTarget, options?: UseResizeObserverOptions): UseResizeObserverReturn;

  <Target extends Element>(
    options?: UseResizeObserverOptions,
    target?: never
  ): UseResizeObserverReturn & { ref: StateRef<Target> };
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.