Skip to content
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

fix: Debounce the resize observer to help with window resizing #18853

Closed
wants to merge 12 commits into from
26 changes: 25 additions & 1 deletion frontend/src/lib/hooks/useResizeObserver.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
import { RefCallback, RefObject, useMemo, useState } from 'react'
import ResizeObserver from 'resize-observer-polyfill'
import { useDebouncedCallback } from 'use-debounce'
import useResizeObserverImport from 'use-resize-observer'

// Use polyfill only if needed
if (!window.ResizeObserver) {
window.ResizeObserver = ResizeObserver
}

export const useResizeObserver = useResizeObserverImport
export type ResizeResponse = {
width?: number
height?: number
}

export function useResizeObserver<T extends HTMLElement>(opts?: {
ref?: RefObject<T> | T | null | undefined
onResize?: (response: ResizeResponse) => void
debounceMs?: number
}): { ref: RefCallback<T> } & ResizeResponse {
const [size, setSize] = useState<ResizeResponse>({})

const setSizeDebounced = useDebouncedCallback((value: ResizeResponse) => setSize(value), opts?.debounceMs ?? 100)

const { ref } = useResizeObserverImport({
ref: opts?.ref,
onResize: (size) => {
opts?.onResize?.(size)
setSizeDebounced(size)
},
})

return { ref, ...size }
}

export function useResizeBreakpoints<T>(
breakpoints: { [key: number]: T },
Expand Down
Loading