DEV Community

Discussion on: `useWindowSize` React Hook To Handle Responsiveness In JavaScript

Collapse
 
lexlohr profile image
Alex Lohr

I would prefer making this more general by taking a configuration object with the desired sizes:

interface Breakpoints {
    [key: string]: number;
}

const isWindowClient = typeof window === "object";

const useWindowSize = (breakpoints: Breakpoints) => {
  const getBreakPoint = 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 resize
    function setSize() {
      setWindowSize(getBreakPoint(window.innerWidth));
    }

    if (isWindowClient) {
      //register the window resize listener
      window.addEventListener("resize", setSize);

      //unregister the listerner on destroy of the hook
      return () => window.removeEventListener("resize", setSize);
    }
  }, [isWindowClient, setWindowSize]);

  return windowSize;
}

export default useWindowSize;
Collapse
 
3sanket3 profile image
Sanket Patel

Cool! Additionally, the way you used Object.values + find + map, refreshed usage of few concepts which I knew but rarely put in practice. Thanks.