-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add debounce to useResizeObserver hook #104
Add debounce to useResizeObserver hook #104
Conversation
I don't really agree with this change, the resize observer may be used for cases where the callback doesn't necessarily cause performance issues when an observed element is resized. E.g. switching states because the target dimensions exceed some boundary. Also, instead of debounce a requestAnimationFrame could be used in most cases. It'll make the resize feel smoother. I prefer to keep the hook more generic so that we have more control over how the callbacks are handled. useResizeObserver(target, useRafCallback(() => {
// Do heavy computation here
}, [])); useResizeObserver(target, useDebounceCallback(() => {
// Do heavy computation here
}, [], 200)); |
Ok, you have a vallid point there but indeed lets have it throttled with requestAnimationFrame then. |
const element = ref.current; | ||
const callbackFunction = | ||
debounceTime === null ? callback : debounce(callback, debounceTime ?? 200); | ||
resizeObserverInstanceCallbacks.set(element, callbackFunction); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will overwrite callbacks that are already added to an element, that could lead to bugs. If we want to keep this implementation we need to support multiple callbacks for a single element.
if (ref.current === null) { | ||
throw new Error('`ref.current` is undefined'); | ||
} | ||
|
||
resizeObserverInstance.observe(ref.current); | ||
if (!resizeObserverInstance) { | ||
resizeObserverInstance = new ResizeObserver((entries, observer) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the previous approach is fine, so I'd like to keep the implementation as simple as possible. Yeah, the old implementation is creating multiple resize observers which may not be necessary, but from a performance point of view it's not likely that we're creating thousands of resize observers on a single page.
Closing this PR because we'll be warning about unthrottled functions via our eslint plugin. |
From a performance perspective we should debounce this hook.
A third parameter is added so the develop can pass the debounced time or ignored at all by adding null. Default debounce time is set at 200ms.