import * as React from "react"; import {createContext, useCallback, useContext, useEffect, useRef, useState} from "react"; import {Dimensions, resizeThresholdExceeded, UseDimensionValues} from "./dimensions"; const initialDimensions = { width: 0, height: 0, } const WindowDimensionsContext = createContext(initialDimensions) interface Props { children: JSX.Element | Array } export function WindowDimensionsProvider(props: Props): JSX.Element { const {children} = props; const currentDimensionsRef = useRef(initialDimensions) const [dimensions, setDimensions] = useState(initialDimensions) const updateDimensions = useCallback( () => { const winDim = {width: window.innerWidth, height: window.innerHeight} if (resizeThresholdExceeded(currentDimensionsRef.current, winDim, 2)) { setDimensions(winDim) } }, [currentDimensionsRef] ) useEffect( () => { updateDimensions() window.addEventListener('resize', updateDimensions) return () => { window.removeEventListener('resize', updateDimensions) } }, [updateDimensions] ) return ( {children} ); } /** * React hook that must be used within a {@link WindowDimensionsProvider} * @return The dimensions values of the element */ export function useWindowDimensions(): UseDimensionValues { const context = useContext(WindowDimensionsContext) const {width, height} = context if (width === undefined || height === undefined) { throw new Error("useWindowDimensions can only be used when the parent is a ") } return context }