From 783bcfd7117eed83d7585c8258eea6807f02ce62 Mon Sep 17 00:00:00 2001 From: Leroy Korterink Date: Fri, 9 Feb 2024 11:42:18 +0100 Subject: [PATCH] Memoize resize callback --- src/hooks/useContentRectState/useContentRectState.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/hooks/useContentRectState/useContentRectState.ts b/src/hooks/useContentRectState/useContentRectState.ts index aba3ff5..f663073 100644 --- a/src/hooks/useContentRectState/useContentRectState.ts +++ b/src/hooks/useContentRectState/useContentRectState.ts @@ -1,4 +1,4 @@ -import { useRef, useState } from 'react'; +import { useCallback, useRef, useState } from 'react'; import { useMount } from '../../index.js'; import { unref, type Unreffable } from '../../utils/unref/unref.js'; import { useResizeObserver } from '../useResizeObserver/useResizeObserver.js'; @@ -11,12 +11,14 @@ export function useContentRectState(target: Unreffable): DOMRect const [contentRect, setContentRect] = useState(null); const rafRef = useRef(0); - useResizeObserver(target, (entries) => { + const onResize = useCallback((entries) => { cancelAnimationFrame(rafRef.current); rafRef.current = requestAnimationFrame(() => { setContentRect(entries.at(0)?.contentRect ?? null); }); - }); + }, []); + + useResizeObserver(target, onResize); useMount(() => { setContentRect(unref(target)?.getBoundingClientRect() ?? null);