DEV Community

Discussion on: Creating Custom Hooks with React.js

Collapse
 
link2twenty profile image
Andrew Bone

Hi, this a nice way to keep track of the screen size though I would add it's important to remove event listeners when you detach the hook. You'd do that by having a return in your useEffect.

import { useEffect, useState } from "react";

export useWindowWidth() {
    const [width, setWidth] = useState(window.screen.width);

    useEffect(() => {
        const updateWidth = () => setWidth(window.screen.width);
        window.addEventListener('resize', updateWidth);
        return () => window.removeEventListener('resize', updateWidth);
    },[]);

    return width;
}
Enter fullscreen mode Exit fullscreen mode

Also it might be worth looking at matchMedia as that will allow you to do more things.

Collapse
 
kuvambhardwaj profile image
Kuvam Bhardwaj

Thanks for pointing that out, quite an important one, left that my bad