Skip to content

Commit

Permalink
fix: infinite loop on useResizeObserver that would repeatedly re-inst…
Browse files Browse the repository at this point in the history
…antiate resize observer instance
  • Loading branch information
jerelmiller committed Sep 10, 2020
1 parent f1951ca commit 8df3506
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/hooks/useResizeObserver.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { useLayoutEffect, useState, useRef } from 'react';
import { useLayoutEffect, useState } from 'react';

// ResizeObserver is not available at build time
const ResizeObserver = global.ResizeObserver || class ResizeObserver {};

const useResizeObserver = () => {
const ref = useRef(null);
const [height, setHeight] = useState(0);
const [ref, setRef] = useState(null);
const [entry, setEntry] = useState(null);

// ResizeObserver is not available at build time
const ResizeObserver = global.ResizeObserver || class ResizeObserver {};
useLayoutEffect(() => {
const resizeObserver = new ResizeObserver(([entry]) => setEntry(entry));

const resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
setHeight(entry.contentBoxSize.blockSize);
});
});
if (ref) {
resizeObserver.observe(ref);
}

useLayoutEffect(() => {
resizeObserver.observe(ref.current);
}, [resizeObserver]);
return () => resizeObserver.disconnect();
}, [ref]);

return [ref, height];
return [setRef, entry];
};

export default useResizeObserver;

0 comments on commit 8df3506

Please sign in to comment.