React Tutorials

React Js Create and Use Own Custom Hook Tutorial

This definitive guide will help you learn how to create and use custom hook in React application using the default useState() hook.

In React, Hooks are simple functions that allow you to initiate React state, furthermore gives you the freedom to manage the lifecycle of a component.

There are two primary paradigms, classes, and hooks if you have ever worked on a class component in React. Then you must know hooks don’t work with classes; if you write code in functional components, then only hooks are for you.

React offers tons of pre-defined hooks that help manage a functional component’s behavior. If you have worked with React before, then you must be aware of the following hooks:

  • useEffect Hook
  • useRef Hook
  • useCallback Hook
  • useMemo Hook
  • useContext Hook
  • useReducer Hook

But do you know you can also create your own custom hook in React application? Well, that’s true, sometimes you might get into a peculiar situation where you have to manage the behavior of a component.

In that case, you can build a custom hook and handle its behavior based on your React app requirements.

Let us find out how to do it?

React Js Build and Use Custom Hook Tutorial

  • Step 1: Set Up React Project
  • Step 2: Add Bootstrap Package
  • Step 3: Create Hook File
  • Step 4: Use Custom Hook
  • Step 5: Run React Server

Set Up React Project

In order to set up the new React app, you must set up Node and npm on your development system.

If node and npm are installed, open your code editor, and go to your terminal app.

Start writing the provided command, and run the command afterwards.

npx create-react-app react-blog

After the create-react-app tool downloaded the new project.

Ensure that you have got inside the project directory.

cd react-blog

Add Bootstrap Package

If you want to develop UI components at exponentially high speed. The Bootstrap library is the best option. However, it is not just the only solution.

In the below command section, you see a command you have to run that command to install the package.

npm install bootstrap

Installing bootstrap is not enough, it has to be registered in App.js file.

After this, you won’t have to write custom CSS to create the user interface components.

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

Now, Bootstrap is fully up and running and ready to conquer the UI part of our small app.

Create Hook File

In your project directory, create another directory name it hooks. In this folder, we are going to create and keep the custom hook file.

Next, create the useCounter.js file; you have to import the useState hook in this file.

Eventually, create a custom function and write the given code to form your own custom hook.

import { useState } from 'react'

export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })

  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }

  return { addCount, onCounterClick }
}

Use Custom Hook

We have successfully created the hook in react, and now you will find out how to use the custom hook in the main app js component.

Open the app.js file and add the code into the file.

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'

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

  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>

      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>

      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

Run React Server

The counter is ready, you can test only after running the React development server.

To start the react app server, you need to run the following command from the command prompt.

npm start

Conclusion

In this React custom hook tutorial, we gave you a demo of building your own custom hook in React. We created a counter clock hook, where a counter number increases with every click.

Apart from that, we also learned how to use a custom hook in React component through this practical code example.

We tried our best to share and persuade regarding all the processes, hope you love this guide.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago