All files / src/components/ui/hooks use-resize-observer.ts

0% Statements 0/17
0% Branches 0/4
0% Functions 0/5
0% Lines 0/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                                     
import { useState, useEffect, useRef, RefObject } from "react";
 
interface Size {
  width: number | undefined;
  height: number | undefined;
}
 
const useResizeObserver = <T extends HTMLElement>(): [RefObject<T>, Size] => {
  const [size, setSize] = useState<Size>({
    width: undefined,
    height: undefined,
  });
  const ref = useRef<T>(null);
 
  useEffect(() => {
    Iif (ref.current && typeof ResizeObserver === "function") {
      const observer = new ResizeObserver((entries) => {
        window.requestAnimationFrame(() => {
          Iif (entries.length === 0) return;
          const { width, height } = entries[0].contentRect;
          setSize({ width, height });
        });
      });
 
      observer.observe(ref.current);
 
      return () => observer.disconnect();
    }
  }, []);
 
  return [ref, size];
};
 
export default useResizeObserver;