Skip to content

Commit

Permalink
Fix resize observer (#166)
Browse files Browse the repository at this point in the history
* Fix resize observer

* Fix unused import
  • Loading branch information
zachhannum authored Dec 2, 2022
1 parent c477524 commit 76e70be
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions app/renderer/hooks/useResizeObserver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useLayoutEffect, useState, useMemo, RefObject } from 'react';
import { debounce } from 'lodash';
import { useRef, useState, useMemo, RefObject, useEffect } from 'react';
import { throttle } from 'lodash';

const useResizeObserver = (
ref: RefObject<HTMLElement>,
Expand All @@ -9,11 +9,14 @@ const useResizeObserver = (
const [width, setWidth] = useState<number>();
const [height, setHeight] = useState<number>();

const resizeObserver = useRef(
new ResizeObserver((entries) => handleResize(entries))
);

const onResize = (entries: ResizeObserverEntry[]) => {
if (!Array.isArray(entries)) {
return;
}

const entry = entries[0];
setWidth(entry.contentRect.width);
setHeight(entry.contentRect.height);
Expand All @@ -23,16 +26,14 @@ const useResizeObserver = (
}
};

const handleResize = useMemo(() => debounce(onResize, wait), [callback]);
const handleResize = useMemo(() => throttle(onResize, wait), [callback]);

useLayoutEffect(() => {
useEffect(() => {
if (!ref.current) {
return;
}

const RO = new ResizeObserver((entries) => handleResize(entries));
RO.observe(ref.current);
}, [ref, handleResize]);
resizeObserver.current.observe(ref.current);
}, []);

return [width, height];
};
Expand Down

0 comments on commit 76e70be

Please sign in to comment.