import React, { ForwardedRef, ReactNode, forwardRef, useEffect, useLayoutEffect, useRef, useState } from "react";

export default function useInWidthRange(threshold: number) {
    const areaRef = useRef<HTMLDivElement>(null)
    const [inRange, setInRange] = useState<boolean | undefined>(undefined)
    
    function SizeWrapper(props: {children: ReactNode }) {
        return (
            <div ref={areaRef}>{props.children}</div>
        )
    }
      
    useEffect(() => {
        function updateState() {
            if (areaRef.current) {
                const width = areaRef.current.offsetWidth
                setInRange(width <= threshold)
            }
        }
        updateState()
        addEventListener("resize", updateState);
        return () => {
            removeEventListener("resize", updateState)
        };
    }, [areaRef, threshold, setInRange])

    return {SizeWrapper, inRange}
}