Custom hooks in React

Photo by Mael BALLAND on Unsplash

Nowadays you can see hooks everywhere in most React codebases. The hooks made it very easy to write code and cut down a number of lines. If you are heavily dependent on hooks and get tired of using hooks in third-party packages for your every smallest problem, this article is for you, as we are going to see how you can write your own custom hook. Custom hooks make it easy to apply custom logic on top of hooks and reduce your code size even more.

First of all, what is a custom hook, in simple language based on my knowledge:

Custom hook is extracting any logic with hook and/or combination of hooks and making it reusable.

In this article, I am going to show you how you can create your own hook in an example of managing a modal state. Before we dive into creating one let’s have a glance at a problem we are facing.

Working with real-world projects you probably have to deal with a lot of modals. And managing their state can be simple but after a while, you will find yourself doing the same thing over and over, like this:

As you can see, you probably use at least one of these functions in your modal-related components. It is okay if you copy-paste these functions across your components but why make your life harder when you can write custom hooks :)

Let's start creating our custom hook. It is a good use case to create a new file for each hook, so let's create our file in this path /hooks/useModal.js , and don’t forget to start hook name with the “use” word, as it is an unwritten rule among react developers.

As I mentioned custom hooks are just functions and they don’t need a React component to exist, also we can use other hooks inside them. First, we declare our state to handle modal visibility. Also, we can pass arguments in our hooks, we use it to pass the default value for our modal state in case we might need it. If this argument is not present we also assign a fallback value. We might as well need to write our functions to handle modal state.

In order to use modal states and actions, we need to return all of the necessary states and functions inside a single object.

I hope you aren’t, but if you are confused about the syntax we used on the return statement, it basically means this:

Now we can use our custom hook where ever we want without extra lines of code.

Well done, now we have our reusable custom hook to manage modal states without extra lines of code. Although I couldn’t break it down into more understandable pieces, I hope this demonstration of custom hook which we can use in the real-world could serve for you as a solid example of your way of creating your own.

Look forward to your responses to this article, and would constantly update and correct any mistakes that might occur.

React dev.