Izhaki / useSize

A react hook to obtain DOM elements' size.
MIT License
0 stars 0 forks source link
hooks react size

useSize

GitHub Workflow Status

A react hook to obtain DOM elements' size.

Ultimately, a compositional take on react-sizeme, barring components (why?).

Features:

Install

npm install @izhaki/use-size

Usage

Size Once

Will only size the component upon mount.

import useSize from '@izhaki/use-size';

function SizeOnce() {
  const { ref, size } = useSize();
  return <div ref={ref} />;
}

With ResizeObserver

Use the native ResizeObserver as a resize detector.

import useSize from '@izhaki/use-size';
import resizeObserver from '@izhaki/use-size/detectors/resizeObserver';

function ResizeObserver() {
  const { ref, size } = useSize({
    detector: resizeObserver(),
  });
  return <div ref={ref} />;
}

With Throttle

import useSize from '@izhaki/use-size';
import resizeObserver from '@izhaki/use-size/detectors/resizeObserver';
import { throttle } from '@izhaki/use-size/regulators';

function ResizeObserverWithThrottle() {
  const { ref, size } = useSize({
    detector: resizeObserver({ regulator: throttle(100) }),
  });
  return <div ref={ref} />;
}

With Debounce

import useSize from '@izhaki/use-size';
import resizeObserver from '@izhaki/use-size/detectors/resizeObserver';
import { debounce } from '@izhaki/use-size/regulators';

function ResizeObserverWithDebounce() {
  const { ref, size } = useSize({
    detector: resizeObserver({ regulator: debounce(100) }),
  });
  return <div ref={ref} />;
}

⚠️ Prefer throttle over debounce, unless your view takes a noticeable time to render (say, 15000 SVG nodes or somesuch).

Using ERD

import useSize from '@izhaki/use-size';
import erd from '@izhaki/use-size/detectors/erd';
import { throttle } from '@izhaki/use-size/regulators';

function ErdWithThrottle() {
  const { ref, size } = useSize({
    detector: erd({ regulator: throttle(100) }),
  });
  return <div ref={ref} />;
}

Why no Components?

Components add to the API surface, specifically as there are rather few scenarios to cover:

Writing all of these components with useSize is cheap (a few lines of code), and each component can be tailored to specific needs.

Example of a component that adds a div to the DOM ```javascript import useSize from '@izhaki/use-size'; import resizeObserver from '@izhaki/use-size/detectors/resizeObserver'; import { throttle } from '@izhaki/use-size/regulators'; function Sizer({ children }) { const { ref, size } = useSize({ detector: resizeObserver({ regulator: throttle(100) }), }); return
{children}
; } ```