Skip to content

Commit

Permalink
fix: use ResizeObserver instead of window resize event listener
Browse files Browse the repository at this point in the history
  • Loading branch information
obecker committed Nov 6, 2024
1 parent f125267 commit 75a926c
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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<HTMLElement> {
accessibility?: boolean
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 75a926c

Please sign in to comment.