Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Custom Hooks in React

How to Create Custom Hooks in React

In this part, we will learn about custom hooks in react, Since we have learned so much about our React hooks, and we have covered almost all types of hooks (it is possible I could have missed some). So it’s time to learn how we can make our own hook, and how can we use it?

There are tons of article on react custom hooks like, how can we make it and how it works, but I’ll try my best to explain everything in very simple manner.

What are Custom Hooks in React?

Custom hooks in React are nothing but a simple function. Yes, you read it right. Custom hook is a function whose name starts with use, Also they can call other hooks like useState, useEffect etc.

Need of Custom Hooks in React

Now the question is raised, why do we even need to build custom hooks in react, and what’s special about it? So the answer is, custom hooks helps us in code reusability, and we don’t have to write larger codes to perform some task again and again. Also, we can do same thing by using component and props, but custom hook is the efficient way to save the time.

For example, suppose we are making some type of application in which we need to show time in 2 components of our application, then what will you do is you will write code in both component separately, right? but what if we write this code once and use in both component? yeah, this is what custom hook will do. you just need to create a function and write the logic once. And you just need to call this function in both components.

There are Some advantages of using Custom Hooks:

  • Reusability — we can use the same hook or code of block again and again, without writing the code again.
  • Clean Code — extracting all the component logic into a hook will provide a cleaner codebase.
  • Maintainability — It is always easy to maintain since we have only one file which includes the logic, so we just need to change that logic once, and it would be applied on all connected components
  • Great Community — You can find the tons of custom hooks available on internet today, and also you can use them too.

Note: Custom Hooks Name Should have prefix use, Which is the convention.

Creating Custom Hooks in React

Let’s just create our very simple custom hook and jump into the codes:

Custom.js

import {useState , useEffect} from "react";

// Remember to start the name of your custom hook with "use"
function useCustomHook(initializer , componentName){
	const [counter , setCounter] = useState(initializer);
	
	// Increases the value of counter by 1
	function resetCounter(){
		setCounter(counter + 1);
	}
	

	useEffect(() => {
		// Some logic that will be used in multiple components
		console.log("The button of the "
		+ componentName + " is clicked "
		+ counter + " times.");
	} , [counter , componentName]);
	
	// Calls the useEffect hook if the counter updates
	return resetCounter;
}

export default useCustomHook;

Component1.js

import React from "react";

// importing the custom hook
import useCustomHook from "./Custom";

function FirstComponent(props){

	// ClickedButton = resetCounter;
	const clickedButton = useCustomHook(0 , "FirstComponent");
	
	return (
		<div>
			<h1> This is the First Component</h1>
			<button onClick={clickedButton}>
				Click here!
			</button>
		</div>
	);
}

export default FirstComponent;

Component2.js

import React from "react";

// Importing the custom hook
import useCustomHook from "./Custom";

function SecondComponent(props){

	// ClickedButton = resetCounter;
	const clickedButton = useCustomHook(0 , "SecondComponent");
	
	return (
		<div>
			<h1> This is the Second Component</h1>
			<button onClick={clickedButton}>
			Click here!
			</button>
		</div>
	);
}

export default SecondComponent;

App.js

import React from 'react';
import './App.css';
import FirstComponent from './Component1';
import SecondComponent from './Component2';

function App(){
	return(
		<div className='App'>
		<FirstComponent />
		<SecondComponent />
		</div>
	);
}
	
export default App;

In the above example, we have our custom hook you can make for anything you want, but we have created here for counting that much time the button clicked. Also, we have two components in which we have a button. Okay, So we want to count the clicks on the button on each component button, So we have called this custom hook in these two components.

Here we have created an object in which we are calling our custom hook, or for simplicity we are calling the function from custom.js. We are running our object when we click the button or onClick event. After we click on the button, the object will run in which we have called the custom hook who takes two arguments, one initial value and the other one component name.

So the hook’s whole logic will run here and increment the value of click as we wrote in the logic, and also print the message in the console again we have mentioned it in our custom hook logic. you can omit the props in our function which I have provided.

Output

Custom Hooks in React

Check out video reference here:

Default image
reactjsguru
Articles: 44

Leave a Reply

Your email address will not be published.