-
Notifications
You must be signed in to change notification settings - Fork 114
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: infinite loop on useResizeObserver that would repeatedly re-inst…
…antiate resize observer instance
- Loading branch information
1 parent
f1951ca
commit 8df3506
Showing
1 changed file
with
14 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |