I would prefer making this more general by taking a configuration object with the desired sizes:
interfaceBreakpoints{[key:string]:number;}constisWindowClient=typeofwindow==="object";constuseWindowSize=(breakpoints:Breakpoints)=>{constgetBreakPoint=useMemo((width:number)=>Object.values(breakpoints).find(([_,size])=>width<=size).map(([id])=>id),[breakpoints]);const[windowSize,setWindowSize]=useState(isWindowClient?getBreakPoint(window.innerWidth):undefined);useEffect(()=>{//a handler which will be called on change of the screen resizefunctionsetSize(){setWindowSize(getBreakPoint(window.innerWidth));}if(isWindowClient){//register the window resize listenerwindow.addEventListener("resize",setSize);//unregister the listerner on destroy of the hookreturn()=>window.removeEventListener("resize",setSize);}},[isWindowClient,setWindowSize]);returnwindowSize;}exportdefaultuseWindowSize;
I would prefer making this more general by taking a configuration object with the desired sizes:
Cool! Additionally, the way you used
Object.values + find + map
, refreshed usage of few concepts which I knew but rarely put in practice. Thanks.