TypeOfNaN

Writing a Custom useWindowSize React Hook

Nick Scialli April 18, 2020🚀 3 minute read

If you're enjoying this blog, please consider one or both of the following:

One of the coolest parts about React Hooks is that you can create your own! In this post, we’ll quickly roll our own useWindowSize hook.

What useWindowSize Will Do

Today we’re creating the useWindowSize custom hook because we’d like to make sure we always have access to our window innerHeight and innerWidth properties when they change. To do this, we’ll tap into the window’s onresize event listener.

Writing the Hook

Since we need to maintain the window size information, we’ll use useState and default it to a two element array consisting of the initial window .

const { useState } = React;

function useWindowSize() {
  const [size, setSize] = useState([window.innerHeight, window.innerWidth]);
  return size;
}

Of course, this won’t be dynamic. To be dynamic, we’ll want to use the window resize event handler. Now, we only need to set the event listener once, so we’ll do this with a useEffect hook with an empty dependency array.

const { useEffect, useState } = React;

function useWindowSize() {
  const [size, setSize] = useState([window.innerHeight, window.innerWidth]);
  useEffect(() => {
    const handleResize = () => {
      setSize([window.innerHeight, window.innerWidth]);
    };
    window.addEventListener('resize', handleResize);
  }, []);
  return size;
}

Awesome, so now we’ve added an event listener and we setSize whenever our window is resized.

There’s one last thing we need to do: add a cleanup function to our useEffect hook to make sure we remove the event listener when our component unmounts.

const { useEffect, useState } = React;

function useWindowSize() {
  const [size, setSize] = useState([window.innerHeight, window.innerWidth]);
  useEffect(() => {
    const handleResize = () => {
      setSize([window.innerHeight, window.innerWidth]);
    };
    window.addEventListener('resize', handleResize);
    // Clean up!
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  return size;
}

See It in Action

Our final code:

const { useEffect, useState } = React;

function useWindowSize() {
  const [size, setSize] = useState([window.innerHeight, window.innerWidth]);
  useEffect(() => {
    const handleResize = () => {
      setSize([window.innerHeight, window.innerWidth]);
    };
    window.addEventListener('resize', handleResize);
    // Clean up!
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  return size;
}

const App = () => {
  const [height, width] = useWindowSize();
  return (
    <div className="box">
      <h1>useWindowSize Hook</h1>
      <p>
        height: {height}
        <br />
        width: {width}
      </p>
    </div>
  );
};

In codepen:


Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Powered by Buttondown.