ZeeCoder / use-resize-observer

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

Use a single ResizeObserver instance #26

Closed alatielle closed 4 years ago

ZeeCoder commented 4 years ago

I don't think attaching extra props to native objects like an HTMLElement is a good idea. I was thinking more of creating some sort of a registry to keep track of observed elements with a WeakMap or something like that. 🤔

alatielle commented 4 years ago

Keeping track of observed elements seems a bit redundant, as ResizeObserver already does just that? As for an attached method, elements might get a prop with this name in the future, prefixing it like ‘_handleResize’ should help. What other concerns do you have?

ZeeCoder commented 4 years ago

Just doesn't feel right to mutate native objects. Feels similar to adding stuff to global / window.

hadeeb commented 4 years ago

What do you think about dispatching a custom event on the element and adding a listener for it in the hook?

ZeeCoder commented 4 years ago

Honestly I'm just not convinced this would worth doing at this point, regardless of the solution. On the whole internet I've only seen that single comment I've linked to that argues it's more performant having a single instance. Non of the more popular measuring libraries utilising ResizeObservers use a single instance either, and I see no issues anywhere related to performance.

Anyway, here are some thoughts:

All in all at the current state I think it's not worth the effort.

Maybe if someone made performance benchmarks where it's clear that this would become a real-life bottleneck I'd consider it, but at the moment it feels like way too much work for way too little.

ZeeCoder commented 4 years ago

I thought I solved this for a second.

I could add a callbacks array, and a single RO that simply calls all callbacks within this array, when changes are detected. Then all the hook instances need to do is add / remove callbacks as needed.

However within the callback the hooks add, it needs to find the entry that's relevant for the given hook, based on the element observed.

This can be done by using a for loop over the entries array, until target === observed element.

This means that as more hooks (and therefore more observed elements) are added, the entries array might grow in size as well.

☝ This might be something worth looking into though, might not be such a big issue.

Only if a LOT of elements change within the same tick, which would mean that all of these hook-added callbacks would need to loop through the entries array to find only the relevant entry for themselves.

Again, these are the sort of things that really need benchmarking. 😅

ZeeCoder commented 4 years ago

See https://github.com/ZeeCoder/use-resize-observer/issues/24