From 33b02b98205ab4c26c3ef0f07cf6d660a2726cad Mon Sep 17 00:00:00 2001 From: Fernando Natividade Date: Fri, 22 Jul 2022 14:33:07 -0300 Subject: [PATCH] add debounce support for ResizeObserver --- src/hooks.js | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/hooks.js b/src/hooks.js index 671bc5e..efe8818 100644 --- a/src/hooks.js +++ b/src/hooks.js @@ -1,8 +1,14 @@ import { select } from 'd3-selection'; import { useEffect, useRef, useState } from 'react'; +import debounce from 'lodash.debounce'; import ResizeObserver from 'resize-observer-polyfill'; -export function useResponsiveSvgSelection(minSize, initialSize, svgAttributes) { +export function useResponsiveSvgSelection( + minSize, + initialSize, + svgAttributes, + debounceTime = 0, +) { const elementRef = useRef(); const [size, setSize] = useState(initialSize); const [selection, setSelection] = useState(null); @@ -46,16 +52,19 @@ export function useResponsiveSvgSelection(minSize, initialSize, svgAttributes) { updateSize(width, height); // Update resize using a resize observer - const resizeObserver = new ResizeObserver(entries => { - if (!entries || entries.length === 0) { - return; - } + const resizeObserver = new ResizeObserver( + debounce((entries) => { + if (!entries || entries.length === 0) { + return; + } + + if (initialSize === undefined) { + const { width, height } = entries[0].contentRect; + updateSize(width, height); + } + }, debounceTime) + ); - if (initialSize === undefined) { - const { width, height } = entries[0].contentRect; - updateSize(width, height); - } - }); resizeObserver.observe(element); // Cleanup