Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active July 28, 2022 06:55
Show Gist options
  • Save sekoyo/c8579667e8a8bd7817c1b4d5b274eb4c to your computer and use it in GitHub Desktop.
Save sekoyo/c8579667e8a8bd7817c1b4d5b274eb4c to your computer and use it in GitHub Desktop.
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 };
}
@sekoyo
Copy link
Author

sekoyo 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