From 564d6473a8b9a345a68b569af662c5faac89e60f Mon Sep 17 00:00:00 2001 From: Zack Stickles Date: Tue, 8 Sep 2020 14:56:30 -0700 Subject: [PATCH] feat: resize observer hook --- src/hooks/useResizeObserver.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/hooks/useResizeObserver.js diff --git a/src/hooks/useResizeObserver.js b/src/hooks/useResizeObserver.js new file mode 100644 index 000000000..267369d62 --- /dev/null +++ b/src/hooks/useResizeObserver.js @@ -0,0 +1,20 @@ +import { useLayoutEffect, useState, useRef } from 'react'; + +const useResizeObserver = () => { + const ref = useRef(null); + const [height, setHeight] = useState(0); + + const resizeObserver = new ResizeObserver((entries) => { + entries.forEach((entry) => { + setHeight(entry.contentBoxSize.blockSize); + }); + }); + + useLayoutEffect(() => { + resizeObserver.observe(ref.current); + }, []); + + return [ref, height]; +}; + +export default useResizeObserver;