How To Make Custom Hooks in React

How To Make Custom Hooks in React

Taking Control: Creating Custom Hooks to Simplify React Development

Intro

Isn't it cool to create your own hooks in your React app? Is it even possible? Is it even true? Yes, we can create custom hooks in React. So, what are we waiting for let's create...

Rules for Creating a Custom Hook

There are rules for everything, so here are the rules for custom hooks in React:

  1. Name your custom hooks with the prefix "use" to indicate that it's a hook. For eg., useCustomHook.

  2. Only calls hooks from React Functions.

Set Up React App

To create your react app, you can either use vite or create-react-app

  • For vite run the following command:-

    npm create vite@latest my-react-app -- --template react

  • For create-react-app run the following command:-

    npx create-react-app my-app

Creating Custom Hooks

Create a folder named hooks in the src folder.

Let's create our custom hooks

  1. Custom hook for getting the current height & width of the browser window

    The function of this hook is to give the current height and width of the browser.

    Let's name it useDimensions.jsx

    Create useDimensions.jsx in hooks folder

    To get the height and width, we have window.innerWidth and window.innerHeight properties in JavaScript.

    Here's what the file will look like:

     import { useEffect, useState } from "react";
    
     const useDimensions = () => {
       const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
       const handleDimensions = () => {
         setDimensions({width: window.innerWidth, height: window.innerHeight});
       };
       useEffect(() => {
         window.addEventListener("resize", handleDimensions);
         return () => {
           window.removeEventListener("resize", handleDimensions);
         };
       }, []);
       return dimensions;
     };
    
     export default useDimensions;
    

    To use this hook, import this in the App.jsx file

     import useDimensions from "./hooks/useDimensions";
     function App() {
       const dimensions = useDimensions();
       return (
         <div>
           <ul>
             <li>Width : {dimensions.width}</li>
             <li>Height : {dimensions.height}</li>
           </ul>
         </div>
       )
     }
    
     export default App;
    
  2. Custom hook for getting the coordinates of the mouse pointer

    The function of this hook is to get the current position of the mouse pointer in the browser window.

    We will name it useMousePointer.jsx

    Create useMounterPointer.jsx in hooks folder

    Here's what the file will look like:

     import { useEffect, useState } from "react";
    
     const useMousePointer = () => {
       const [position, setPosition] = useState({ x: 0, y: 0 });
       const handleMouseMove = (e) => {
         setPosition({ x: e.clientX, y: e.clientY });
       };
    
       useEffect(() => {
         window.addEventListener("mousemove", handleMouseMove);
    
         return () => {
           window.removeEventListener("mousemove", handleMouseMove);
         };
       }, []);
    
       return position;
     };
    
     export default useMousePointer;
    

    To use this hook, import this in App.jsx file

     import useMousePointer from "./hooks/useMousePointer";
    
     function App() {
       const coordinates = useMousePointer();
       return (
         <div>
           <ul>
             <li>X : {coordinates.x}</li>
             <li>Y : {coordinates.y}</li>
           </ul>
         </div>
       );
     }
    
     export default App;
    
  3. Custom hook for checking online or offline

    The function of this hook is to find whether we are online or offline on the browser.

    We will name it useIsOnline.jsx

    Create useIsOnline.jsx in hooks folder

    Here's what the file will look like:

     import { useEffect, useState } from "react";
    
     function useIsOnline() {
       const [online, setOnline] = useState(window.navigator.onLine);
       useEffect(() => {
         window.addEventListener("online", setOnline(true));
         window.addEventListener("offline", setOnline(false));
       }, []);
       return online;
     }
    
     export default useIsOnline;
    

    To use this hook, import this in App.jsx file

     import useIsOnline from "./hooks/useIsOnline";
    
     function App() {
       const online = useIsOnline();
       return <div>User Online : {online}</div>;
     }
    
     export default App;
    

By creating three custom hooks, we've unlocked the power of reusable logic in our React applications. The beauty of custom hooks lies in their versatility - just like components, we can create as many as we need to streamline our code and improve maintainability. Let's continue harnessing this power to build even more efficient and scalable React applications!

Thank you for taking the time to read this blog! Your feedback is invaluable to me, so please feel free to share any thoughts or suggestions you have. I appreciate your support!