From 75a926ca1a1351bdaecdefb833957013b32d8e30 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 | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index c294fd6..009ccf1 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) + if (elementRef.current == null) return - return () => window.removeEventListener('resize', clampLinesDebounced) + const observer = new ResizeObserver(debounceFn(clampLines, debounce)) + observer.observe(elementRef.current) + return () => observer.disconnect() }, [clampLines, debounce]) return hasText ? createElement(is, clampProps, textRef.current) : null