UNPKG

@faceless-ui/slider

Version:

A React library for building every kind of slider

55 lines 2.14 kB
import { useCallback, useEffect, useRef, useState } from "react"; export const useBreakpoints = (props) => { const [propsToUse, setPropsToShow] = useState(props); const animationRef = useRef(null); const requestAnimation = useCallback(() => { const { breakpoints } = props; if (animationRef.current) cancelAnimationFrame(animationRef.current); if (breakpoints) { animationRef.current = requestAnimationFrame(() => { const matchedBreakpoints = Object.keys(breakpoints).map((breakpoint) => { const matches = window.matchMedia(breakpoint).matches; if (matches) return breakpoint; return undefined; }).filter(Boolean); if (matchedBreakpoints.length === 0) { setPropsToShow(props); } else { const lastMatch = matchedBreakpoints[matchedBreakpoints.length - 1]; const breakpointProps = breakpoints[lastMatch]; setPropsToShow(Object.assign(Object.assign({}, props), breakpointProps)); } }); } setPropsToShow(props); }, [props]); const requestThrottledAnimation = useCallback(() => { setTimeout(() => { requestAnimation(); }, 500); }, [requestAnimation]); useEffect(() => { window.addEventListener('resize', requestAnimation); window.addEventListener('orientationchange', requestThrottledAnimation); requestAnimation(); return () => { window.removeEventListener('resize', requestAnimation); window.removeEventListener('orientationchange', requestThrottledAnimation); }; }, [ requestAnimation, requestThrottledAnimation, ]); useEffect(() => { () => { if (animationRef.current) { cancelAnimationFrame(animationRef.current); } }; }, []); return propsToUse; }; //# sourceMappingURL=useBreakpoints.js.map