Zach WhiteNotesGitHub

React custom hook: useWindowResize()

12 June, 2020 - 1 min read

I was looking for a way to track the window resolution of a React app in real time, and stumbled upon this custom hook on Stack Overflow:

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

Then if you just import it and instantiate it, you can grab the width and height that it returns and do useful things with it. Here's an example of importing it and using it to conditionally render something:

import useWindowDimensions from "../../utils/hooks/useWindowDimensions"

  const { height, width } = useWindowDimensions()
  if (width >= 576) {
    return (
      <SectionLayout>
        <SectionRow

        //// stuff

Obviously for most window-resizing concerns, a simple media query is usually your best bet. But you never know- it pays to have a few extra tricks up your sleeve too.

-ZW

© 2020, Zach White