npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-dimensions

v1.2.1

Published

useDimensions - a React Hook to measure DOM nodes

Downloads

40,901

Readme

useDimensions - a React Hook to measure DOM nodes

Travis npm package Coveralls

Demo

👉 check out demo page to see useDimensions in action

Backstory :P

The other day I wanted to measure some DOM nodes. This is useful when you have to align items, or respond to browser width, or ... lots of reasons okay.

I had to align a curvy line with elements that aren't under my control. This little stepper component uses flexbox to evenly space circles, CSS layouting aligns the title, and you see where this is going.

SVG in the background detects position of itself, positions of the title and circle, and uses those to define the start and end line of my curve. 👌

Many ways you can do this.

@lavrton linked to a list of existing NPM packages that sort of do it. @mcalus shared how he uses react-sizeme to get it done.

All great, but I wanted something even simpler. I also didn't know about them and kind of just wanted to make my own.

Here's an approach I found works great

useDimensions hook

useDimensions source

Yep that's it. It really is that simple.

👉 GitHub link

  • useRef creates a React.ref, lets you access the DOM
  • useState gives you place to store/read the result
  • useLayoutEffect runs before browser paint but after all is known
  • getClientBoundingRect() measures a DOM node. Width, height, x, y, etc
  • toJSON turns a DOMRect object into a plain object so you can destructure

Here's how to use it in your project 👇

First, add useDimensions to your project

$ yarn add react-use-dimensions
or
$ npm install --save react-use-dimensions

Using it in a component looks like this

import React from "react";
import useDimensions from "react-use-dimensions";

const MyComponent = () => {
    const [ref, { x, y, width }] = useDimensions();

    return <div ref={ref}>This is the element you'll measure</div>;
};

useDimensions returns a 2-element array. First the ref, second the dimensions.

This is so multiple useDimensions hooks in the same component don't step on each others' toes. Create as many refs and measurement objects as you'd like.

const MyComponent = () => {
    const [stepRef, stepSize] = useDimensions();
    const [titleRef, titleSize] = useDimensions();

    console.log("Step is at X: ", stepSize.x);
    console.log("Title is", titleSize.width, "wide");

    return (
        <div>
            <div ref={stepRef}>This is a step</div>
            <h1 ref={titleRef}>The title</h1>
        </div>
    );
};

Disabling live updates

By default useDimensions live updates its measurements on every scroll and resize event. This can lead to a lot of re-rendering, if you aren't careful.

I recommend feeding the dimensions you care about into your list of useEffect triggers. That is the best way to ensure good performance.

If however, you don't want that and know you just need to measure once, useDimensions supports an optional liveMeasure argument.

const MyComponent = () => {
    const [stepRef, stepSize] = useDimensions({ liveMeasure: false });

    // useDimensions never updates and won't trigger re-renders
    console.log("Step is at X: ", stepSize.x);

    return (
        <div>
            <div ref={stepRef}>This is a step</div>
        </div>
    );
};

License

MIT License of course.