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

onResize is not called on mount #88

Closed lishine closed 2 years ago

lishine commented 2 years ago

onResize is not called on mount in case when useResizeObserver is given an external ref

const ref = useRef<HTMLDivElement | null>(null)
    useResizeObserver({
        onResize: ({ height = 0, width = 0 }) => {
            setPanelHeight(height)
            setPanelWidth(width)
        },
        ref,
    })

vs

    const { ref } = useResizeObserver({
        onResize: ({ height = 0, width = 0 }) => {
            setPanelHeight(height)
            setPanelWidth(width)
        },
    })
ZeeCoder commented 2 years ago

Interesting, depending on the exact circumstances this may or may not work, since we cannot detect (and react to) changes in ref. (It would help a lot if you could reproduce in a codesandbox.)

The ref you use in the second example works, because it's a ref callback, and so every time the elements changes (or set with a delay), the hook is notified.

I recommend either sticking to the second pattern, or if you have your own ref that you have to use, to merge the callback ref you get from the hook with it, before setting it on the element.

lishine commented 2 years ago

I indeed now start using the merge callback pattern, but would rather not to. Wouldn't you think it could be implemented such that useResizeObserver will include mount triggered useEffect(()=>{},[]) to call the provided to the hook callback ?

ZeeCoder commented 2 years ago

I can't reproduce this issue, see this codesandbox of an example where I pass in a ref to the hook, and onResize is called on the initial mount as well as on resizes.