ZeeCoder / use-resize-observer

A React hook that allows you to use a ResizeObserver to measure an element's size.
MIT License
644 stars 42 forks source link

Add optional effect to useResizeObserver #25

Closed danni closed 4 years ago

danni commented 4 years ago

We've been using useResizeObserver to track when to trigger a side effect, and so end up with code like this:

  const axisRef = useRef();
  const cursorRef = useRef();
  const { width: axisWidth } = useResizeObserver({ ref: axisRef });

  // Reset the axis if the width changes
  useEffect(() => {
    if (cursorRef.current !== null) {
      cursorRef.current.reset();
    }
  }, [axisWidth]);

It would be convenient if we could simply provide this effect to the resize observer.

ZeeCoder commented 4 years ago

I'm not sure I follow, seems like you're calling a reset on a ref in reaction to the measured element's changes in width? I don't see how that's something the resize observer can be responsible for? Seems like a very specific logic for your app.

I'd recommend just creating your own hook on top of this one to make it more convenient, if you find it becoming a regular pattern, as this lib is meant to be as low-level as possible.

danni commented 4 years ago

The reset is specific, but the general case of a property called effect or onResize would be useful. That runs inside the existing effect in the hook. It would pass width and height and let you do what you will.

It would allow you to create a pattern like this:

const { ref: axisRef } = useResizeObserver({ onResize: width => cursorRef.current && cursorRef.current.setWidth(width) });

I could wrap this if I need it more than once. Although I've been inspired for how I can probably use the property directly with a bit of refactoring.

ZeeCoder commented 4 years ago

Ah yeah I get what you want now. Could be done. I just need to make sure not to return width/height in the return object then, as that becomes unnecessary. 🤔

Even better, I think with a callback I can implement a better throttled / debounced solution as well, as the current recommendation triggers a render, whether or not the return values of width / height are actually used or not: https://github.com/ZeeCoder/use-resize-observer#throttle--debounce

ZeeCoder commented 4 years ago

Added in v6

ZeeCoder commented 4 years ago

You might want to check out this demo @danni : https://codesandbox.io/s/use-resize-observer-throttle-and-debounce-8uvsg

danni commented 4 years ago

Nice!