How to create and implement a Custom Hook in React application?

Custom Hook

In simple terms React Hooks are functions. When you include them in your component or within another Hook, they allow you to make use of React internals and parts of the React lifecycle with native Hooks like useState and useEffect.

What is a Custom Hook?

A Custom Hook allows you to extract some components’ logic into a reusable function.

Custom Hooks are nothing but a JavaScript function, use while creating a React app. If we have common logic that we want to share between components then we use custom Hooks. The main goal is creating code reusability.

Why we use custom Hooks?

Custom Hooks are used when you notice that you require the same code again and again. You may think that we can use the function for eliminating code, so why we create a Hook? It’s because of Hooks rules:

 Only call Hooks from React function

Rules for custom Hooks

  • Only call Hooks at the top level.
  • Only call Hooks from React function.
  • Create a Hook using the name start with a “use” keyword.

Create custom Hooks

Let’s create a custom Hook in the newly created React app. We need to create an app using create React command.

Step 1: Create an app “Hooks-demo” using the below command:

npx create-React-app Hooks-demo

After running the above command successfully,

cd hooks-demo
npm start

Step 2:  Create a file “useOrderCount.js” to write our custom Hook logic:

Go to the src folder and create file “useOrderCount.js” to write the code for custom Hook and write the below code:

import { useState } from 'react';

function useOrderCountHook() {
   const [orderCount, setOrderCount] = useState({ count: 0 });
   
   const changeOrderCount = () => {
      setOrderCount({ count: orderCount.count + 1 }) 
    }   

return { orderCount, changeOrderCount };
}

export default useOrderCountHook;

Step 3: Use “useOrderCountHook” in our app:

Go to the file src/App.js and delete all codes in file src/App.js and write the below code:

import React from 'react';
import useOrderCountHook from './useOrderCount';
import './App.css';

function App() {
   const orderHook = useOrderCountHook();   

    return (
     <div>
       <h1>count:{orderHook.orderCount.count}</h1>
       <button type='button' onClick
         {orderHook.changeOrderCount}>Increment</button>
    </div>
   );
}

export default App;

Conclusion

In conclusion, You can use this Hook in any component. This Hook is reusable.

For more details about React hook development: Click Here