useDimensions

Use this hook to debounce a value only updating it once within the given delay. Useful if you need to request data when an input updates but don't want to fetch the new data on every keystroke.

This hook is heavily inspired by Reach's useRect hook.

Usage

import { useRef } from 'react';
import { useDimensions } from '@fransvilhelm/hooks';
const SquareWithDimensions = () => {
const ref = useRef(null);
const rect = useDimensions(ref);
return (
<div ref={ref}>
{rect?.width} px / {rect?.height} px
</div>
);
};

Example

300px / 300 px

Parameters

useDimensions accepts one required parameter – a React ref object attached to a DOM element – and two optional parameters related to observing dimensions changes.

ParamTypeRequiredDefaultDescription
refReact.RefObject<Element>true-Ref object attached to a dom element
observebooleanfalsefalseSet to true to subscribe to changes on the elements dimensions
callback(rect: DOMRect) => voidfalse-Callback called every time the rect is updated

Returns

useDimensions returns an client rect object.

PropTypeDescription
rectDOMRect \| nullrect object containing dimensions and position of the current element. This is the same object as one gets from element.getBoundingDOMRect()