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

use-observe-resize

v1.0.1

Published

React hooks to use ResizeObservers.

Downloads

15

Readme

use-observe-resize

React hooks to use ResizeObservers.

import { useState } from "react";
import { useObserveResize } from "use-observe-resize";

const Example = () => {
  const [width, setWidth] = useState(null);

  const observeResize = useObserveResize((entry) => {
    setWidth(entry.contentRect.width);
  });

  return <div ref={observeResize}>{width}</div>;
};

useObserveResize

Observe an element for resizes.

function useObserveResize(
  onResize: ObserveResizeCallback,
  options?: ResizeObserverOptions
): RefCallback<Element>;

type ObserveResizeCallback = (
  entry: ResizeObserverEntry,
  resizeObserver: ResizeObserver
) => void;

Parameters

onResize: The function called when the element resizes. This function does not need to be stable or memoized (don't call useCallback). The function takes two parameters:

options: The optional options parameter for ResizeObserver.observe().

Returns

Returns a callback ref. The element passed to the callback will be observed. This function changes if the options object changes.

useResizeObserver

Creates a ResizeObserver.

function useResizeObserver(
  onResize: ResizeObserverCallback
): [() => ResizeObserver, MutableRefObject<ResizeObserver | undefined>];

Parameters

onResize: The function called when observed elements resize. Same type as the callback parameter for the ResizeObserver constructor.

Returns

Returns an array with two items:

  1. A stable lazy getter function that will create a ResizeObserver if one hasn't been created yet. This function is stable for all renders.
  2. A reference object with .current set to a ResizeObserver or undefined.

Example

From the Deep Dive: How to manage a list of refs using a ref callback from the beta react docs:

import { useResizeObserver } from "use-observe-resize";

const Example = (props) => {
  const refItemMap = useRef(null);
  if (refItemMap.current === null) {
    refItemMap.current = new Map();
  }

  const [getResizeObserver] = useResizeObserver((entries) => {
    for (let entry of entries) {
      // do w/e
    }
  });

  return (
    <ul>
      {props.items.map((item) => (
        <li
          key={item.id}
          ref={(element) => {
            const resizeObserver = getResizeObserver();
            if (element) {
              refItemMap.current.set(item.id, element);
              resizeObserver.observe(element);
            } else {
              element = refItemMap.current.get(item.id);
              refItemMap.current.delete(item.id);
              resizeObserver.unobserve(element);
            }
          }}
        >
          {item.text}
        </li>
      ))}
    </ul>
  );
};

FAQ (or questions I think might come up)

"ResizeObserver loop limit exceeded" errors

These errors are often benign, but they can be annoying if you have window.onerror handlers. Before you ignore these errors, you should try to implement your layout to be top-down. This would avoid the loop limit errors because nodes that are at or above a previously processed depth wouldn't have resize events.

If your layout can't be top-down or requires 2 passes to stabilize, you can either filter these errors out or try the following pattern to avoid them:

import { useObserveResize } from "use-observe-resize";

const Example = () => {
  const observeResize = useObserveResize((entry, resizeObserver) => {
    // use entry to make state updates, etc.
    // ...

    // unobserve this element until the next animation frame
    resizeObserver.unobserve(entry.target);
    requestAnimationFrame(() => {
      // it should be okay to re-observe at this point to avoid loop limit errors
      resizeObserver.observe(entry.target);
    });
  });

  return <div ref={observeResize} />;
};

Ref for the observe target

If you need a ref to the observe target, you can create another callback ref that stores the element and sets up the ResizeObserver.

import { useRef, useCallback } from "react";
import { useObserveResize } from "use-observe-resize";

const Example = () => {
  const ref = useRef(null);

  const observeResize = useObserveResize((entry) => {
    // ...
  });

  const setRef = useCallback(
    (element) => {
      observeResize(element);
      ref.current = element;
    },
    [observeResize]
  );

  return <div ref={setRef} />;
};