Custom Hooks In React

Custom Hooks 

  • React provides the way to store the logic in function and reuse the function in the form of Custom Hooks.
  • With the help of custom hooks we can reuse the same code in different function or component.
  • If you perform some operation which is used in almost all of the components and uses the build-in hooks, then instead of repeating the logic at every place, we can create custom hooks and re-use it anywhere we need.

How to create custom Hooks ?

  • Custom hooks are same as JavaScript functions whose name starts with the “use”
  • You can pass parameters to it
  • You can return anything from custom hooks
  • You can also use other hooks inside custom hooks

Example: Create custom hook to get the window size.

  • useWindowResize.js
import { useState, useEffect } from "react";

export const useWindowResize = () => {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

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

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

  return {
    width,
    height,
  };
};
  • Usage of the custom Hook (App.js)
import React from "react"
import {useWindowResize} from './useWindowResize ';

function App() {
  const windowSize = useWindowResize();
  return (
    <div style={{backgroundColor:'pink'}}>
      {windowSize.width<600 ?
        <h1>Small Screen</h1>  :
        <h1>Big Screen</h1>
      }
    </div>
  );
}
export default App

We can now use the “useWindowResize” hook in various components where we need to perform some operation based on windowSize.

OUTPUT:-

Conclusion:-

Custom hooks are easy to implement and reduces the unwanted code duplication from the code. It makes the code optimize and reusable.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories