From ad951b9ace2b90f05c2b6d874e379bc317e9345a Mon Sep 17 00:00:00 2001 From: Oliver Becker Date: Tue, 5 Nov 2024 20:05:23 +0100 Subject: [PATCH] fix: use ResizeObserver instead of window resize event listener Fixes https://github.com/microlinkhq/nanoclamp/issues/33 --- src/index.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index c294fd6..969563e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { createElement, useRef, useEffect, useCallback, useMemo } from 'react' +import { createElement, useCallback, useLayoutEffect, useMemo, useRef } from 'react' interface Props extends React.HTMLAttributes { accessibility?: boolean @@ -93,13 +93,14 @@ const NanoClamp = ({ updateTextRefs(textPlusEllipsis) }, [ellipsis, hasText, lines, text]) - useEffect(() => { + useLayoutEffect(() => { clampLines() - const clampLinesDebounced = debounceFn(clampLines, debounce) - window.addEventListener('resize', clampLinesDebounced) - - return () => window.removeEventListener('resize', clampLinesDebounced) + if (elementRef.current) { + const observer = new ResizeObserver(debounceFn(clampLines, debounce)) + observer.observe(elementRef.current) + return () => observer.disconnect() + } }, [clampLines, debounce]) return hasText ? createElement(is, clampProps, textRef.current) : null