Skip to content

Commit

Permalink
fix(core): avoid occasional "ResizeObserver loop" error
Browse files Browse the repository at this point in the history
This error is hard to reproduce, but it's a straightforward workaround
to make sure the observer doesn't try to update when it can't within
the given frame.
  • Loading branch information
Sam Jones committed Apr 5, 2021
1 parent 29e7531 commit 6dc5412
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions packages/core/src/hooks/useMeasure.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ import ResizeObserver from 'resize-observer-polyfill'

export const useMeasure = () => {
const measureRef = useRef(null)
const animationFrameId = useRef(null);
const [bounds, setBounds] = useState({
left: 0,
top: 0,
width: 0,
height: 0,
})
const [observer] = useState(() => new ResizeObserver(([entry]) => setBounds(entry.contentRect)))
const [observer] = useState(() => new ResizeObserver(([entry]) => {
// wrap this call in requestAnimationFrame to avoid "Resize Observer loop limit exceeded"
// error in certain situations
animationFrameId.current = requestAnimationFrame(() => {
setBounds(entry.contentRect)
})
}));

useEffect(() => {
if (measureRef.current) {
observer.observe(measureRef.current)
}

return () => observer.disconnect()
return () => {
animationFrameId.current && cancelAnimationFrame(animationFrameId.current);
observer.disconnect()
}
}, [])

return [measureRef, bounds]
Expand Down

0 comments on commit 6dc5412

Please sign in to comment.