Home > ReactJS > Build React Custom Hook – Step by Step Guide

Build React Custom Hook – Step by Step Guide

In this tutorial, you will learn about react hooks and how you can build your own custom hook, and when to use it.

React hooks are reusable functions and it’s a new part of react from starting version 16.8 and they are useful to manage state and other react features without class components. There are many built-in react hooks but useState(), useEffect(), useContext(), useReducer() are mostly useable.

You can also make your own custom hook in react and use it wherever you want. So in this tutorial, I will show you how you can build a custom hook. Before starting to build hooks, you should know in which situation you need custom hooks.

When to Use Custom React Hook

As I said above hooks are reusable functions, so using the react custom hook you can extract the unique logic into reusable functions.

In simple words, you can say that when you have multiple components with repeated logic every time then you can build your own custom react hook.

In that custom hook, you can add that same repeated logic in one component and then use that component as a hook in your other components.

Build React Custom Hook

React custom hooks will let you make special and common functionality logic into reusable functions and use them in your react application. You can add new features to your react application using the custom hooks.

The custom hook’s name always starts with the “use” word. We will use the built-in useState() and useEffect() hooks to build custom own hook (useTabNotification()) We will see the below example code step by step.

Use case: This example of react custom hook is useful when you want to show up the notification in your browser’s tab title. The notification will blink at every specified time. Let’s build it.

Create Component File

Let’s create a component file called “useTabNotification.js“. You can place this file in your components folder or wherever you want. Import the useState, useEffect, and useRef components from react at top of this file.

Then we will write the logic for our custom react hook and then we can import this component file into other components to use it.

Get Document Title

To get the document title, we will simply use the “title” property of the document like “document.title“. It will give the browser’s active tab document title.

And we will make a simple logic here to check if the notification is set or not and display them accordingly.

Create useTabNotification() Function

Now let’s create a useTabNotification() arrow function and export it as default and also have the default interval in milliseconds.

Initialize the notification state with a default null value and declare the intervalRef variable using the useRef hook.

Set Interval to Display Notification

We will use useEffect() hook to set up a notification message and notification interval. We will check that if have a notification message and not any ref then set up the message for notification in the current ref.

If not have a notification message then reset the timer to clear the interval of reference and set up the value as null.

In the above code, we used the two useEffect() hooks, the first is used for setting up the notification message and interval time and the second is for clearing the interval of ref on the first render if any.

We also used the resetTimer() function in the above code to clear the interval. Let’s make this function now.

Create Reset Timer Function

Let’s now create a function resetTimer() and clear the interval of the current ref using the clearInterval() function. And set up the intervalRef.current value as null.

Create Clear Notification Message

Create a clearNotification() function to clear the notification message and set up the original title of the document and set the state of notification as null.

Make all the above steps together into a “useTabNotification.js” file and it’s ready to use. See the following code together.

useTabNotification.js

Use useTabNotification() Hook

Now we have successfully created the custom useTabNotification() hook in react, let’s now use it in another component to see if it’s working.

Create a “Dashboard.js” component file and import the useTabNotification() custom hook into this file. And create two buttons to set up the notification message and stop the notification message.

Dashboard.js

Some Rules of React Hooks

As you see above you can easily build a custom react hook but while building new custom hooks, you have to keep the following rules in your mind. You can use the linter package to enforce these rules automatically.

  • Custom hooks start with the word “use”
  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Hooks only work in function components
  • Don’t call Hooks from regular JavaScript functions.

That’s it!!!

Hope it helps to boost your knowledge of react and react hooks. If you have any queries please do let me know in the comment section, and I’ll respond to you as soon as possible.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment