Docs
Measure

Measure

Effortlessly measure and track your component’s dimensions

About

The useMeasure hook monitors and responds to changes in the size of a React component. It uses the ResizeObserver API to track changes in the component’s dimensions (width and height) and keeps them available as state. The returned ref is used on the element whose dimensions you want to measure, making it valuable for responsive design and dynamic layout adjustments.

Return Values

NameTypeDescription
refReact ref objectA React reference that can be attached to a DOM element to observe.
rectobjectAn object containing the width and height of the observed element.

Rect Object Properties

PropertyTypeDescription
widthnumberWidth of the observed element.
heightnumberHeight of the observed element.

Installation

Run the following command:

npx scriptkavi-hooks@latest add measure

Usage

import { useMeasure } from "@/hooks/measure"
import * as React from "react"
 
function Measure({ type = "horizontal" }) {
  const [ref, { width, height }] = useMeasure()
 
  return (
    <figure>
      <figcaption>
        <span>{type}</span>
      </figcaption>
      <article
        ref={ref}
        className={type}
        style={{
          resize: type,
        }}
      >
        {type === "horizontal" ? (
          <label>width: {Math.floor(width)}</label>
        ) : (
          <label>height: {Math.floor(height)}</label>
        )}
      </article>
    </figure>
  )
}
 
export default function App() {
  return (
    <section>
      <h1>useMeasure</h1>
      <p>(Resize the rulers)</p>
      <Measure />
    </section>
  )
}