DEV Community

Cover image for Make your own Custom Hooks in React!
Sumrit Grover
Sumrit Grover

Posted on

Make your own Custom Hooks in React!

React provides many in-built hooks that you can use in your app

But you can also create custom hooks, which helps reduce the amount of code

Custom hooks are similar to functions but usually start with use and may call other in-build hooks as well

Need for Custom Hooks

The main reason why you should be using Custom hooks is to maintain the concept of DRY(Don't Repeat Yourself)

To understand more about DRY and WET refer to the tweet below.

Dry or Wet Code

When and How to use it

If you want to share the logic between different components, we can extract that to a separate function.

Because custom hooks are JS functions the rules of hooks apply to it as well.

Rules of Hooks are-

  1. Never call Hooks from inside a loop or condition

  2. Hooks should sit at the top-level of your component

  3. Only call Hooks from React functional components

  4. Never call a Hook from a regular function

  5. Hooks can call other Hooks

Building your Custom Hook

Making your own hook is similar to making a JavaScript function, but its name starts with use.

Inside them, you can use any other hook, take anything as parameters, return anything you want it to return.

Put it to the test

Let us create a custom hook that uses useEffect hook that updates the title of the document

This is how you traditionally write the code

Image description

Creating the custom hook

What we would do is take out the incrementCount function and put it in a separate file and pass the count state in it.

Like this

Image description

Call the Custom hook

Call the hook in your file as you would normally call a JS function

Image description

Conclusion

This is how easy it is to make your own custom hooks and integrate them into your application

If you want to try and experiment with this code, here is the link to the same

Code Base

Top comments (0)