Skip to content
Snippets Groups Projects
Select Git revision
  • main default protected
1 result

useWidth.ts

Blame
  • useWidth.ts 765 B
    import {useEffect, useState} from "react";
    
    export const useWidth = <T extends HTMLElement>(it: T | null) => {
        const [width, setWidth] = useState<number>(0);
        useEffect(() => {
            let animationFrame: number | null = null;
            const listener = () => {
                animationFrame = window.requestAnimationFrame(() => {
                    animationFrame = null;
                    setWidth(it?.offsetWidth || 0);
                });
            };
            listener();
            window.addEventListener("resize", listener);
            return () => {
                window.removeEventListener("resize", listener);
                if (animationFrame !== null) {
                    window.cancelAnimationFrame(animationFrame);
                }
            }
        }, [it]);
        return width;
    }