DEV Community

Cover image for React Custom Hooks (useWindowResize)
sundarbadagala
sundarbadagala

Posted on • Updated on

React Custom Hooks (useWindowResize)

INTRO

Hello World! 👋
Now onwards I want to start a new series named React Custom Hooks. In this series I want to post different ReactJS custom hooks, their coding and their use cases.

Today's Custom Hook is useWindowResize.

USAGE

This hook is very helpful to the developers when they want to know browser screen width and height. As a frontend developer I am always have to check the screen width to test web responsiveness. We know that we have media queries in css to handle responsiveness but sometimes have to handle from JavaScript side also. That time this hook will very helpful to handle page layouts or design changes based on screen width what we get from this hook.

CODE

import { useEffect, useState } from "react";

export const useWindowResize = () => {
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const handleResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    handleResize();

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return { width, height };
};
Enter fullscreen mode Exit fullscreen mode

USE CASE

import { useWindowResize } from "./useWindowResize";

function LogoComponent() {
  const { width } = useResize();

  const getLogo = () => {
    if (width <= 480) {
      return "mobile logo";
    } else if (width <= 768 && width >= 480) {
      return "tablet logo";
    } else {
      return "desktop logo";
    }
  };
  return getLogo();
}

export default LogoComponent;
Enter fullscreen mode Exit fullscreen mode

OUTPUT

Image description

I hope you people understand the useWindowResize hook. We will meet with another hook in another post.

Peace 🙂.

Top comments (0)