Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useResizeObserver hook for React
import { useRef, useCallback, useEffect, useState } from 'react';
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer';
const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;
export default function useResizeObserver() {
const [size, setSize] = useState({ width: 0, height: 0 });
const resizeObserver = useRef(null);
const onResize = useCallback(entries => {
const { width, height } = entries[0].contentRect;
setSize({ width, height });
}, []);
const ref = useCallback(
node => {
if (node !== null) {
if (resizeObserver.current) {
resizeObserver.current.disconnect();
}
resizeObserver.current = new ResizeObserver(onResize);
resizeObserver.current.observe(node);
}
},
[onResize]
);
useEffect(() => () => {
resizeObserver.current.disconnect();
}, []);
return { ref, width: size.width, height: size.height };
}
@DominicTobias
Copy link
Author

DominicTobias commented Nov 6, 2019

Usage:

function Something() {
  const resizeObserver = useResizeObserver();

  return (
    <div ref={resizeObserver.ref}>
      {resizeObserver.width} {resizeObserver.height}
    </div>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment