React.js

Custom hooks in React-js

Welcome readers, in this tutorial, we will create a custom hooks in a React-js application.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. A custom hook in React-js is a javascript function whose name starts with the “use” keyword. Custom hooks in React-js are used to remove the duplicated logic in the component and we can extract that logic to a custom hook.

1.1 Setting up dependencies

To play with react let us set up some of the required dependencies.

1.2.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

1.2.2 Setting up React-js project

Once the Nodejs setup is successful we will use the below command to install the react library and set up the project. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app custom-hook

The above command will take some time to install the react library and create a new project named – custom-hook as shown below.

Fig. 2: Project structure

2. Custom hook in Reactjs

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up the react code

To understand a practical implementation let us go through some hands-on exercises.

2.2.1 Creating the counter custom hook

Add a new class in the src folder responsible to extract the duplicate logic from the component into a custom hook. The file will handle the counter increment or decrement and will return the variables that can be consumed in the component files.

UseCounter.js

import { useState } from "react";

//represents a custom hook.

const UseCounter = () => {
  const [count, setCount] = useState(0);

  const incrementHandler = () => {
    setCount(count + 1);
  };
  const decrementHandler = () => {
    setCount(count - 1);
  };

  return [count, incrementHandler, decrementHandler];
};

export default UseCounter;

2.2.2 Creating the counter1 component

Create a component file in the src folder representing the usage of the custom hook created above.

Counter1.js

import React from "react";
import UseCounter from "./UseCounter";

const Counter1 = () => {
  const [count, incrementHandler, decrementHandler] = UseCounter();
  return (
    <div>
      <h3>{count}</h3>
      <button onClick={incrementHandler}>Increment</button>
      <div> </div>
      <button onClick={decrementHandler}>Decrement</button>
    </div>
  );
};

export default Counter1;

Repeat the same step to create a file representing counter 2. You can download the counter 2 component from the Downloads section.

2.2.3 Creating implementation file

In the App.js component we will include the counter components. The counter component will include a custom hook counter of its own and each counter magic can happen independently.

App.js

import React from "react";
import "./App.css";
import Counter1 from "./Counter1";
import Counter2 from "./Counter2";

const App = () => {
  return (
    <div className="App">
      <h1>Custom hook</h1>
      <Counter1></Counter1>
      <Counter2></Counter2>
    </div>
  );
};

export default App;

3. Run the setup

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000 to avoid the default port clash.

4. Demo

The application will be started in the default browser as shown below and a welcome page with two components will be loaded. If you click on the buttons the counter will either increment or decrement for the respective component.

Fig. 3: Application demo

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a react application and understood custom hooks. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand the custom hook in a react application.

Download
You can download the full source code of this example here: Custom hook in Reactjs

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Focalworks
9 months ago

What components are being included in the App.js component, and how does the use of custom hooks allow independent functionality for each counter component in the given code snippet?

Back to top button