Skip to content

useResizeObserver

Handle the ResizeObserver using this hook.

Parameters

  1. the ResizeObserver callback function.
  2. the ResizeObserver options, as well as the ref object of the target element.

Return Values

NameTypeDescription
refRefObjectthe target element reference.
observerRefObjectthe ResizeObserver object reference.

Example Usage

TIP

Just use useSize if you want to get an element size in a state.

tsx
import { useResizeObserver } from 'react-pre-hooks';

export default function Example() {
  const { ref } = useResizeObserver(entries => {
    const { width, height } = entries[0].contentRect;
    console.log({ width, height });
  });

  return (
    <main>
      <div ref={ref}>Resize the window!</div>
    </main>
  );
}
import { useResizeObserver } from 'react-pre-hooks';

export default function Example() {
  const { ref } = useResizeObserver(entries => {
    const { width, height } = entries[0].contentRect;
    console.log({ width, height });
  });

  return (
    <main>
      <div ref={ref}>Resize the window!</div>
    </main>
  );
}

Released under the MIT License.