React Custom Hooks: A simple intuition if you still can’t hit it off

Skrew Everything
From The Scratch
Published in
8 min readApr 18, 2020

Let’s be honest, React Hooks are awesome 😍 but confusing as hell 😵

Previously, I’ve strictly used Class Components instead of Functional Components even if I didn’t need the lifecycles and state functionality as I’m lazy to refactor my code from functional component to class component if by any chance I ever wanted to introduce lifecycles or/and state functionalities in a component.

When React introduced Hooks, I was reluctant to use them as they were confusing, at least when I read the docs initially.

But hey! Time makes everything better and Hooks are no exception

What changed my mind? Well, boredom of this lockdown🥱. I was so bored that I gave another chance to Hooks and after creating a simple app while learning it, it kind off hit me in the head and now I can see everything around me in Hooks🧑🏻‍🎓.

Ok, I was exaggerating for the effect.

So, let’s look at some points, tips, explanations to understand Hooks as simple as possible.

What are React Hooks anyway?

It’s a new feature(well, not so new. It was released in 2018) to use lifecycles and states in Functional components.

Before the introduction of the Hooks, the only way to use lifecycles and states is through Class component.

Why is everyone losing their minds over Hooks anyway?

If you haven’t, then you have to look at these tweets from 2018 first.

Got it why everyone is losing their minds over Hooks?

If you didn’t then let me tell you what’s going on in the above GIF.

The first part of the GIF uses Class Component and second part uses Functional Component with Hooks. And color codes are used to group lines based on their logic required to do THEIR THING.

If you observe, when using Class Component, the logic of the code is spread all over the component. But, when using Functional Component with Hooks, the logic of the code is confined to their own places.

This greatly increases developer productivity while reading through the code or debugging it. With Hooks, you don’t have to scroll your IDE to relevant sections of the code responsible for its job. If you want to know how a feature works, you just have to look at one place to make sense.

Also, the amount of code to write a component decreases significantly with Hooks as you don’t have to deal with “bind”ings, “constructors”, repeating code in different methods etc.

The best thing about Hooks is: You can create and re-use your custom Hooks in other components, which reduces code duplication substantially.

And also, one more trivial advantage is: you don’t have to shuffle between Class and Functional Components based on your needs. You can just learn Functional Components with Hooks and you can forget about Class Components all together. Unless, you have to maintain your old React code which was written in Classes. But, if you are starting a new project, then you can just write all your components using Functional Components and later if you need lifecycles and state, then use Hooks to introduce them into your already written Functional Component instead of refactoring it into Class Component.

NOTE: If you are a beginner or starting to learn React, then start with the Class Components. Class Components are more detailed and explicit, which helps you to understand the concepts and how things work more concretely. After you grasp how React works, then you can shift to the Hooks.

Before getting into the explanations and intuitions, I hope you know the basic syntax of the useState and useEffect .

If you don’t, then come back after learning the basic syntax. I can explain it though, but there are already numerous wonderful tutorials and articles on the basics of Hooks. Writing them provides no value and diverts the aim of this article, which is to get the intuition but not an another tutorial on Hooks.

The Facebook’s documentation is pretty good actually with some use-cases.

Just don’t go deep. Get the basics on how-to use them. Once you get the intuition here, you will get when-to and then you can learn the more advanced concepts like useReduce .

Let me know in the comments if you would like a tutorial on Hooks too.

Getting the intuition

Let’s look at some code first:

If you are familiar with the Class Components, this is how you must be doing your input handling in your components.

So, what’s wrong in that?

First of all, nothing is wrong with that. If it is wrong, then Facebook wouldn’t have introduced it in the first place.

But when you look at the above code after the introduction of the Hooks, you can realise how the logic is spread across the whole component and there’s a lot of code duplication(we will get to this below) in multiple Class Components.

This is how it looks in Hooks

If you notice, the Hooks gist looks more elegant, concise and cleaner than the Class Component gist.

Whatever I mentioned above is aesthetics. Now, let’s get to the most interesting topic: Reducing code duplication through custom Hooks.

Building your own Hooks lets you extract component logic into reusable functions.

Consider a scenario: You have multiple components in your UI, which takes inputs from the users. Before Hooks, you can only use Class Component to handle input data. So, you have to write the samehandleInputs(event) method logic in every component that takes input from the User. If you have 10 different components in your app, then you have to write the same handleInputs(event) method logic 10 times in those 10 components.

But with custom Hooks, you can write it only 1 time and use it in “N” number of components. This reduces code duplication substantially as mentioned before.

I’ve changed the above Hooks code a little to make it a custom Hook.

Can you comprehend what I did there?

I just removed the logic from the component to its own function so that it can be re-used in our other functional components.

Now, you can move the function useHandleInputs() {...} into another file, and can be import ed into your other components.

And now, we have successfully written our first custom Hook.

How can a normal JavaScript function can maintain state of its own?

If you know React, then this will be your first question after seeing the code above.

Just remember one thing about React Hooks,

React Hooks are plain JavaScript functions, which can maintain their own state and lifecycles, isolated from components.

That’s it! That’s what you need to know to get the intuition on how-to, when-to and what-to use custom Hooks for.

Those custom Hooks works exactly like when a Class Components update it’s state.

The main thing you have to do is, return the state s from your custom Hook to the functional component you want to use it and that’s it.

Whenever the state inside your custom Hooks is changed, your component is re-rendered to reflect the new changes.

If you still haven’t got it, then try to reason this simple code that we always do and also a common practice in React.

We send the states and callbacks from the Class Component to Functional Component as props and whenever a change happens in the Class Component states, the new states are passed to Functional Component as props to re-render to reflect the new state.

If we want to compare our custom Hooks with the above code, then assume:

Class component vs. Functional component with a Custom Hook

The code sections are color coded to group how similar they are in functionality.

Yellow: Maintains the state and passes it to Purple components

Purple: Purple doesn’t have it’s own state but depends on the Yellow’s state to render

In Class Component, the state and lifecycles are tied to its component. So, it can be re-used as a component but can’t be re-used as a logic.

In Custom Hooks, the state and lifecycles are not tied to any component. Custom Hooks can exist individually — logically as a function. So, it can be re-used as a logic in other components.

A tip for writing your own Hooks easily

I know custom Hooks are cool and awesome but don’t always try to write a custom Hook.

First, use the Hooks provided by the React in a Functional Component. Then if you find that it can be re-used in another component, then try to extract it outside of that Functional Component like we did in the above:

  1. We wrote a Functional Component App using useState Hook.
  2. We found out that we can use the handleInputs() function in other Functional Components also.
  3. Extracted that function from our App Functional Component to its own function useHandleInputs() , which is our custom Hook.
  4. Import our custom Hook useHandleInputs() into App Functional Component or any other Functional Components.

Also, you might find in most of the articles/tutorials that custom Hooks are written using useState()and useEffect() in combination always. Writing custom Hooks doesn’t require you to use both useEffect() and useState() Hooks compulsorily. You can use any combination of Hooks. You can either use useEffect() or useState() . You can use both of them. You can even use your own custom Hook to write another custom Hook.

More Resources

React docs has explained custom Hooks with state and lifecycle with a use-case, which is pretty simple and useful. Check it out 👇🏻👇🏻👇🏻

And don’t forget to checkout the 2 rules you have to follow while using Hooks. React docs has pretty good explanation for this also 👇🏻👇🏻👇🏻

I hope this helped you to get the intuition on “How to write your own Hooks”

If you still got any doubts, then comment down🙂

Liked it? Then comment down, 👏🏻👏🏻👏🏻 it and share it!

--

--

Skrew Everything
From The Scratch

A wannabe artist 👨‍🎨, but can’t draw 😫. A wannabe athlete 🏃‍♂️,but can’t run 🥵.Found my peace with coding 👨‍💻 and writing ✍️. Twitter.com/SkrewEverything