A react hook to obtain DOM elements' size.
Ultimately, a compositional take on react-sizeme, barring components (why?).
Features:
npm install @izhaki/use-size
Will only size the component upon mount.
import useSize from '@izhaki/use-size';
function SizeOnce() {
const { ref, size } = useSize();
return <div ref={ref} />;
}
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} />;
}
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} />;
}
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).
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} />;
}
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.