1.0.6 • Published 3 years ago

@izhaki/use-size v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

useSize

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:

  • Do we add an element to the DOM? Which one? How will it be styled?
  • Do we Forward Ref?
  • Do we support render props?
  • What about High Order Components?

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

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 <div ref={ref}>{children}</div>;
}
1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.0.1

3 years ago