useMeasure

Measure an element's dimensions.

https://www.shaktools.com/shak-hooks
Browser

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useMeasure } from "@shak-hooks/usehooks";
Source: packages/react/src/useMeasure.ts

Signature

signature.ts
export function useMeasure<T extends HTMLElement = HTMLElement>(): [
MutableRefObject<T | null>,
Rect
]

Parameters

No parameters.

Returns

[ MutableRefObject<T | null>, Rect ]

Implementation

use-measure.ts
1import { useState, useRef, useEffect } from "react";
2
3export function useMeasure() {
4 const ref = useRef<HTMLElement>(null);
5 const [rect, setRect] = useState({
6 width: 0,
7 height: 0,
8 top: 0,
9 left: 0,
10 bottom: 0,
11 right: 0,
12 x: 0,
13 y: 0,
14 });
15
16 useEffect(() => {
17 if (!ref.current) return;
18
19 const observer = new ResizeObserver(([entry]) => {
20 setRect(entry.contentRect as any);
21 });
22
23 observer.observe(ref.current);
24 return () => observer.disconnect();
25 }, []);
26
27 return [ref, rect] as const;
28}

Advertisement

Google Ads

Usage

example.tsx
1import { useMeasure } from "@shak-hooks/usehooks";
2
3const result = useMeasure();
4// result: [
5 MutableRefObject<T | null>,
6 Rect
7]
8// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy