Custom useResize hook

Anna Vlasenko
2 min readSep 29, 2020

Photo by Nathan Fertig on Unsplash

Hello folks, let’s create useResize hook. Sometimes we need to render an element on our page depends on its width or height. And we can easily and beautifully detect a page’s size without any libraries.

With react hooks we can very elegant implement detecting window resize and reuse it over the app.

Let's create a file and call it useResize.js. The naming convention for react hooks tells us to use the prefix “use” at the beginning of the hook’s name. Any hook is just a function, and in this function, we are going to use react hooks useEffect and useState. We create state size, it will be an array where the first value is window.width, and the second window.height. Size array is a value we want to return from useResize function.

import { useEffect, useState } from “react”;  const useResize = () => {
const [size, setSize] = useState([0, 0]);
return size;
};
export default useResize;

Page with and height we can get with window property innerWidth, as well as we, work with side effect we have to implement it in useEffect hook. For detecting, the page’s resized we can add a listener for DOM resize event, and don't forget to remove lister on component unmount, in useEffect hook possible unsubscribe event in functions return.

import { useEffect, useState } from “react”;const useResize = () => {
const [size, setSize] = useState([0, 0]);
useEffect(() => {
const getSize = () =>
setSize([window.innerWidth, window.innerHeight]);
getSize();
window.addEventListener("resize", getSize);
return () => window.removeEventListener("resize", getSize);
}, []);
return size;
};
export default useResize;

Here is a link to the sandbox.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Anna Vlasenko
Anna Vlasenko

Written by Anna Vlasenko

Frontend Developer | ❤️ React

No responses yet

Write a response