How to Build and Use Custom Hook in React Js App

In this step-by-step post, you will be taught about React custom hooks. More preciously, what are custom hooks? How to create custom hooks in React? How to use own hook in React application.

Hooks play a significant role in managing state, lifecycle and many more in React’s functional component. React offers several pre-defined hooks, which are decisive and allow converting stateless components to functional components.

However, seldom any programming task can come from outside of the pre-defined hooks scope.

You can effortlessly create your own custom Hooks and manage the state or component behaviour.

Thanks to React’s eloquent flexibility.

Hooks work with the functional component; ideally, one thing is to remember that hooks don’t support classes; classes have their own lifecycle methods.

React Js Create Custom Hook Example

  • Step 1: Build React App
  • Step 2: Install Bootstrap Framework
  • Step 3: Create Custom Hook
  • Step 4: Implement Custom Hook
  • Step 5: View App in Browser

Build React App

Before we start writing the code for custom hook, we must make sure we have the node and npm installed on our system.

If the required tools are installed, only then you can create the new react app.

Downloading a fresh react app is easy, and can be done with given command.

We have given a certain name to our app, but you may name it anything.

npx create-react-app react-tube

Once the react-tube app is created, quickly get into the app’s root.

cd react-tube

Install Bootstrap Framework

Bootstrap is CSS framework and mainly used to design the layout of the site.

We are about to take help of this package to design the UI of our small functionality.

Let us type and run the given command to add the package into the app.

npm install bootstrap

Library is easily installed, but our work is not done yet. Following path must be added to App.js file.

import 'bootstrap/dist/css/bootstrap.min.css'

But, If you do not want to use it, then no problem. You can avoid this package and use your custom CSS.

Create Custom Hook File

Now, from here, the actual task starts. First, without further ado, go to the `src` directory, ensure that you create a customHooks/ folder and useProductCount.js file.

The customHooks/useProductCount.js is the file where you will write the code to form the new custom hook.

Hence, do not forget to add the following code into the file.

import { useState } from "react";

export default function useProductCount() {

  const [totalProduct, setProductCount] = useState({ counter: 0 });

  const incrementProduct = () => {
    setProductCount({ counter: totalProduct.counter + 1 });
  };

  return { totalProduct, incrementProduct };

}

This is a pretty basic counter functionality, and a user will click on the button to add the number of items.

We will use the useState hook to set the counter’s initial state; on every click, we will increase the counter to 1.

Implement Custom Hook

We will show you how to use the custom hook in React component.

Import the hook module into the App.js file, declare the hook in the app function and access the hook methods to run the hook counter.

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css'
import useProductCount from './customHooks/useProductCount.js'

export default function App() {
  const hookCustom = useProductCount()

  return (
    <div className="container mt-5">
      <h2 className="mb-2">React Custom Hook Example</h2>

      <div className="col-12">
        Add products: <strong>{hookCustom.totalProduct.counter}</strong>
      </div>

      <button
        type="button"
        className="btn btn-primary mt-3"
        onClick={hookCustom.incrementProduct}
      >
        Update order
      </button>
    </div>
  )
}

View App in Browser

We have created the custom hook, and we are all set to test it out.

But it is only possible, after starting the react server.

You can kickstart the react app by using the suggested command.

npm start

Here is the url that will allow view the app in full action.

http://localhost:3000

Finally, thats what you will see on the browser.

How to Build and Use Custom Hook in React Js App

Summary

In this tutorial, we showed you how to build custom hooks in React using React hooks. We have also learned how to use and reuse custom hooks in React app.

We know you will love this step by step guide, but somehow we missed anything. Don’t hesitate to share your feedback with us.