Custom hooks in react

Custom hooks can be created when you want to avoid duplicate code and functionality in the application. For example - Let us say there are 2 components which need to take action when user resized the window. So we can write a code to add even listener on resize. This code can be put in a custom hook and can be reused in both components.

import { useState, useEffect } from "react";

export const useWindowResize = () => {

  //state to store width and height of window
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

  const functionToCallOnResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };

  useEffect(() => {
    //add resize event listener on component mount
    window.addEventListener("resize", functionToCallOnResize);
   
    //remove resize event listener on component mount
    return () => {
      window.removeEventListener("resize", functionToCallOnResize);
    };
  }, []);

  //return width and height of window after resize event
  return {
    width,
    height,
  };
};



// to use above hook, you can use below syntax

let windowDimensions = useWindowResize()

if (windowDimensions.height <= '400'){
    console.log("Window height less than 400")
}

Complex problems, Simple Solutions