From be964f933c2ccd3c4448b4e1d922ece1cf85b23c Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Wed, 4 Oct 2023 10:05:21 +0800 Subject: [PATCH] Better throttle instead of debounce --- src/utils/useTruncated.js | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/utils/useTruncated.js b/src/utils/useTruncated.js index ca7cda2..e7f7723 100644 --- a/src/utils/useTruncated.js +++ b/src/utils/useTruncated.js @@ -1,27 +1,21 @@ import { useRef } from 'preact/hooks'; -import { useDebouncedCallback } from 'use-debounce'; +import { useThrottledCallback } from 'use-debounce'; import useResizeObserver from 'use-resize-observer'; export default function useTruncated({ className = 'truncated' } = {}) { const ref = useRef(); - const onResize = useDebouncedCallback( - ({ height }) => { - if (ref.current) { - const { scrollHeight } = ref.current; - let truncated = scrollHeight > height; - if (truncated) { - const { height: _height, maxHeight } = getComputedStyle(ref.current); - const computedHeight = parseInt(maxHeight || _height, 10); - truncated = scrollHeight > computedHeight; - } - ref.current.classList.toggle(className, truncated); + const onResize = useThrottledCallback(({ height }) => { + if (ref.current) { + const { scrollHeight } = ref.current; + let truncated = scrollHeight > height; + if (truncated) { + const { height: _height, maxHeight } = getComputedStyle(ref.current); + const computedHeight = parseInt(maxHeight || _height, 10); + truncated = scrollHeight > computedHeight; } - }, - 300, - { - maxWait: 2000, - }, - ); + ref.current.classList.toggle(className, truncated); + } + }, 300); useResizeObserver({ ref, box: 'border-box',