Skip to content

Commit

Permalink
Memoize resize callback
Browse files Browse the repository at this point in the history
  • Loading branch information
leroykorterink committed Feb 9, 2024
1 parent 3e74eb8 commit 783bcfd
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/hooks/useContentRectState/useContentRectState.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -11,12 +11,14 @@ export function useContentRectState(target: Unreffable<Element | null>): DOMRect
const [contentRect, setContentRect] = useState<DOMRectReadOnly | null>(null);
const rafRef = useRef(0);

useResizeObserver(target, (entries) => {
const onResize = useCallback<ResizeObserverCallback>((entries) => {
cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
setContentRect(entries.at(0)?.contentRect ?? null);
});
});
}, []);

useResizeObserver(target, onResize);

useMount(() => {
setContentRect(unref(target)?.getBoundingClientRect() ?? null);
Expand Down

0 comments on commit 783bcfd

Please sign in to comment.