Writing Your Own Custom React Hooks

Let’s extract your components logic into reusable functions.

Aayush Jaiswal
Bits and Pieces

--

Photo by Cameron Kirby on Unsplash

It’s a scary world out there and please don’t tell me you are planning to survive this React World just with the help of classes (of course you can but it will be painful). Hooks are the new trend in React Community and are inevitable for any React developer out there.

Hooks basically put your functions on steroids so that you can stop relying on classes and move on to functions (if you prefer classes over functions then it’s a different story). Hooks will revolutionize how the React code is to be written. Sooner or later, you will have to dive into hooks.

This post is for devs who know what hooks are and have used them before.
If you still haven’t touched it then it’s time you do.

Useful tip: Use Bit to encapsulate components with all their dependencies and setup. Build truly modular applications with better code reuse, simpler maintenance and less overhead.

Custom hooks??

There might be instances where you have been using the same repetitive and redundant stateful logic inside multiple components. We were able to handle this situation by relying on Render props and Higher Order Components. But with hooks, we can do it in a much simpler and cleaner way, Thanks to the Custom hooks.

Okay, But what are they?

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.

Let’s say you have 2 functions (components) which implement some common logic. You can create a third function with this common logic and implement it in the other two functions. After all, hooks are just functions.

Custom hooks means fewer keystrokes and less repetitive code.

Cool, But why it’s high time to write our own custom hooks?

This javascript community is a group of people who run on caffeine and love to open source everything they build.

Yeah, so before you start writing your own custom hooks there is a VERY high possibility that someone has already written it and put it on npm. So if you are doing something new it’s probably not new anymore.

You must have heard about Kent C. Dodds, he is a pretty big deal in React community and I quote the statement he made on his youtube channel during December when hooks were not stable (now they are).

“hooks are not stable, but by the time they are, every hook conceivable will have been written and open sourced already… I’m pretty sure there are at least 10 localstorage hooks on npm already.”

You kidding, right? A minimum of 10 hooks just based on localStorage!! Guys take a break 🙄.

So if you are serious about doing something cool and awesome with hooks, better start now.

This post doesn’t provide you with innovative ideas for writing your own custom hooks but teaches you how to write or build custom hooks by giving some examples.

Let’s jump into some of these examples.

useDocumentTitle hook

Say we have to build a component which on every click increases the count and updates the title of the page with thecount value using hooks. Not a big deal, right.

Counter Component

It works well. I always prefer creating the component first and then extracting out the stateful logic from that function(component) and then putting it into another function(custom hook) and then just doing some refactoring so the component works well with our hook.

Let’s take the useEffect section out of the component and put it inside our new function useDocumentTitle.

useDocumentTitle hook

Simple, but not useful? Where can this be useful?

To show unread messages or notifications on slack or facebook. We can use this useDocumentTitle hook in a place where we get the message and then we call this hook with a count of unread messages and title.

useLocalStorageState hook

Building a Counter component that stores the count in local storage and updates and gets the count value from localStorage.

Counter Component

Get the value from local storage, if it doesn’t exist set it to 0. Update the value on every click in local storage. It is nice but let’s say you have to build another Counter component which increases the value by 5 or the value increase every second. You might find yourself re-writing the localStorage code in every component. Let’s avoid this and write our own custom hook.

useLocalStorageState takes two parameters, one being the key and second the default value. We get the count from localStorage and set it tostate . We use the useEffect hook to set the value in the local storage and finally return out the state and setState method as an array.

useLocalStorage hook

Now, this looks better, you just have to call the hook with the key and a default value. And the key to localStorage is added with the default value and fetched by our hook while the count is updated by the component itself. We put local storage code in our hook and the state updating part in our component.

useUnSplashImages hook

You encountered this problem where you have to create a component to display some images from Unsplash and make another component which is an Unsplash image slider. In these two components, there exists a common stateful logic of getting the images from the API. We can extract this logic in our custom hook useUnSplashImages.

In this hook, we take the secret key and query as parameters. We have three states to worry about loading, error and response data. We make a GET request using axios with the URL and update the state based on response and return an array of our three states which can be destructured in the respective component.

useUnSplashImages hook

And below is how we implement it our component->

Unsplash Component

Our custom hook does the fetching and provides us with the images array, loading status and also with an error status. Remaining logic is handled by the component, we just have to provide the query and the secret key provided by Unsplash. Our component receives the three states and uses them as required. Later on, we can create a slider or loop through the images array to display the images.

useArray hook

I found this hook to be super useful and helps you carry out all the array related tasks easily. Building a todo list was never this easy.

useArray hook

This custom hook is beautiful and easy to comprehend. This hook takes the initial array as a parameter and provides the methods to modify it. add adds an element to the existing array, clear empties the array and there are much more methods like these.

Let’s implement this hook in the component:

Todo component

We get the array methods object in the todos variable. We have a button which on click has the todos.add method that adds a random number in the array. In the same fashion, all the other methods are implemented.

See, it’s a beautiful hook created by Kitze.

You can take this hook or any other custom hook to a whole new level with your imagination. It’s much easy and cleaner than render props and HOC.

Conclusion

In this article, we learned about some cool stuff related to React’s Custom Hooks. Building these hooks seems like an art to me. Hope you liked this article and learned something new and if you did clap your heart out and follow me for more content on Medium and as well as on Twitter. Please feel free to comment and ask anything. Thanks for reading 🙏 💖.

--

--