How to create React’s Custom Hooks

Muhammad Basir Baig
3 min readNov 1, 2020
Photo by Tatiana Rodriguez on Unsplash

In this post you will learn how to create your own custom hooks in react .

Note:

This article is for those developers who have used basic react knowledge and have worked with hooks as this article will not cover the react basics.

What are hooks in short ?

Hooks are a new addition in React 16.8.React Hooks are in-built functions that allow React developers to use state and lifecycle methods inside functional components, they also work together with existing class based components code.

With React Hooks developer can easily use functional components for keeping state , handling logic and also rendering the ui.

React Custom Hooks Overview

These are normal JavaScript functions which can use other hooks inside of it and contain a common stateful logic that can be reused within multiple components. These functions are prefixed with the word use.

Now you have got the basic concept of React Hooks , lets dive into making our own custom hook.

Example

Let say we have an application with15 views and in each view we have to render a list of unique names.

So with the help of creating a custom hook we can write our logic into one custom hook instead of writing the same lines of code to render the list in each of 15 views and use this custom hook in each view of our application.

Moving forward I am going to give “useDisplayList” name to my custom hook .

In this hook we will take api url as parameter and we have three states loading , list and error . We make get request to jsonfakeapi using axios and set the loading state to true , on response we will filter out the list with unique records , and will update the list state with new filtered list and loading state to false.

If our request fails for some reason then we will update the error state with error text and loading state to false.

And in any our component we can use our custom hook like this

As you can see in our component we are passing the url to our custom hook and it is fetching data from api and providing us with the list , loading and error state . Now our component is receiving three states and are
handling the remaining logic like mapping and rendering the list into ui.

Conclusion

In this article, we learned about creating and using our own React’s Custom Hook . Hope you have learned something new today and if you liked this article please make a clap and follow me for more content on Medium . Thanks for reading 🙏 💖.

--

--