Skip to content

Commit

Permalink
Added a debounce to the default resize observer
Browse files Browse the repository at this point in the history
  • Loading branch information
benjackwhite committed Nov 23, 2023
1 parent fc0107f commit 9e764d3
Showing 1 changed file with 25 additions and 1 deletion.
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> | RefObject<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

0 comments on commit 9e764d3

Please sign in to comment.