Clasping the React Hooks — Part 1

Neha Singh
Globant
Published in
9 min readJul 17, 2020
medium.com

I am sure that as a developer till now you must have bookmarked at least a dozen websites for understanding React Hooks. Implemented it either in your project or as a POC. React hooks have been around for quite some time now. So, Of course, you must have aced them! Right? Well, not exactly! In fact, most developers are still confused about its implementation.

I have tried my level best to explain and demystify React hooks in multiple parts of this article. So, here I start, stay hooked!

BUT WHY HOOKS?

https://zbigatron.com/

Have you ever been in a situation wherein you are working with the functional component, and need some kind of update in the behavior which can be easily handled through the component state, but due to unavailability of state inside the functional component, you end up updating your component to class component?

Have you ever gone through the pain of rewriting a similar kind of code inside different lifecycle methods to achieve the required behavior on the prop or state update?

Have you ever gone through the pain of managing large code and difficulty of reusing component’s logic?

If you are a React developer these all are usual problems that you must be facing daily, isn’t it?

It is quite frustrating, right?

What if I tell you Hooks are something that came to rescue us from all such problems. It let us use all React features inside the functional component without having to update it to the class component. Isn’t it amazing?

OK OK, BUT WHAT ARE HOOKS? 😵

According to React’s official documentation:

Hooks are a new feature addition in React 16.8. They let you use state and other React features without writing a class.

In other words, React Hooks are javascript functions that solve a wide range of problems that we’ve encountered while working with functional components by providing us the privilege to use all the features of React such as state, side-effects, reusable logic, lifecycles, context, etc. inside the functional component.

Apart from this, Hooks also let us organize all related code together, unlike class components where all the related code are usually kept inside different lifecycle methods making it difficult to follow. By using hooks all the lifecycle methods can be replaced using a single Hook reducing the lines of code and complexity and making our code more readable.

We’ll see this in much detail later.

Also, since Hooks are regular JavaScript functions, you can combine built-in Hooks with your own “custom Hooks”.

Custom Hooks are something that we can create to reuse the component’s logic. This lets us reduce complexity by sharing reusable logic across the application.

There are a couple of more reasons for introducing Hooks. Some of them are listed below:

TO AVOID DEALING WITH ‘this’ KEYWORD

To work with classes you have to understand how ‘this’ keyword works in javascript which is very different from how it works in other languages.

People can learn prop, state, and unidirectional data flow in React but struggles to implement class components.

STATE IN FUNCTIONAL COMPONENT

Previously we could use state only within Class components. But, with Hooks, we can now use state within functional components using the useState hook.

HOT RELOADING WITH CLASSES

It is also observed that classes don’t minify very well and make hot reloading very unreliable. With Hooks since you don’t have to work with classes anymore, you don’t face these problems.

REUSING COMPONENT’S LOGIC

Customs hooks allow us to reuse the component’s logic without changing our Component hierarchy.

BACKWARD COMPATIBILITY

React Hooks are 100% backward compatible and work alongside our existing code. If you have been working with React, and have been using class-based components, there is no rush to move to hooks. Hooks are optional and while working with Hooks you don’t have to necessarily rewrite the complete code, rather you can use hooks only with a few components.

But, before getting started on Hooks, there are a couple of things that you should keep in mind — Hooks don’t work with classes, you should use hooks when working with functional components. You should call Hooks at the top level it means it should not be called inside loops, conditions, nested functions, etc

Let’s begin with our first React Hook and try to understand it with some examples

UseState Hook

STATE..!! Okay, if you have worked on class components you must be familiar with setState() which schedules an update to the component’s state, and when state changes, the component re-renders.

But we cannot have the state or setState() inside the functional component, this is where useState Hook comes into the picture.

How ❓❓

Okay.. we’ll see an example with setState() and then we will see how we can rewrite it using useState Hook.

cheezburger.com

Below is an example of a COUNTER where the count is initialized by zero and every time on click of the button, the counter increments its value by 1.

In the above example, you can see, we’ve first initialized the count value using this.state inside the constructor, then on button click we’ve called the setCount() method to update the state and inside that we’ve used setState() method to update the count value to currentValue + 1;

Now, we can rewrite the above example using the useState hook as follows

As you can see here, by using the useState function inside the functional component the lines of code have been reduced pretty much and it is more readable now.

Also in classes, the state is always an object, but with hooks, the state is not necessarily an object, it can be of any type.

Syntax:

With useState hook the initial value of the state, the method to update the state, and the current value of the state everything can be written in a single line of code.
This syntax is known as Array Destructuring which is one of the features of ES6.

useState with the previous value of state

Sometimes we need to access the previous value of the state to update the current state, this can be done by passing a function to useState in the previous example. This function will have access to the previous value, and return an updated value.

Here’s an example of a counter component that updates the state using useState hook with the previous value of the state

useState with Object

Now we’ll see another example that makes use of the useState Hook when our State is an Object. Let’s try to print the full name of a person, based on values entered in the firstName and LastName field.

We’ll take values from the state and update it onChange of input fields.

In the above example, the state object is holding firstName and lastName properties, and these values are updated as soon as the user enters something in the input field.

Now, you might have noticed that we are merging states inside the onChange function using the spread operator with fullName i.e. {…fullName}. It is because unlike setState() the useState hook doesn’t automatically merge state objects. Hence we have to do manual merge by using a Spread Operator as you can see in the above example.

When dealing with Objects or Arrays, always make sure to spread your state variable and then call the setter function

useEffect Hook

The useEffect hook lets us perform side effects and all features of lifecycle methods inside functional components.

It also lets us organize all related code together unlike classes where all related code are kept in different lifecycle methods.

Here’s an example:

Consider updating the document title to the current input field value, on an initial render we want to set the title to initial value of the state, so this code goes inside componentDidMount which will execute only once in the component lifecycle then this document title will be updated later.

For that, the same piece of code will be written inside componentDidUpdate. This lifecycle method is called every time the component updates and is perfect for updating the document title.

Also, let’s take another side effect with a timer that logs some string value in a particular interval of time and then clearing it on unmount.

Here you can see the same code twice in two different lifecycle methods also unrelated codes are kept together in one lifecycle method. It’s kinda weird, right?

This problem can be solved using the useEffect hook. Let’s see how.

In the above example, you can see how we have replaced the usage of two lifecycle methods with only one function which is known as useEffect Hook.

Now the question arises, Is it possible to execute this function only once during mount, and what if we want to execute it conditionally if only particular prop/state updates?? The answer is yes, yes it is possible to execute it conditionally.

For running useEffect conditionally we need to pass an additional parameter which is an array. In this array, we specify either prop or state which we need to watch for. Then this function will be executed only if those states or props are updated.

If you want to run useEffect only on the component mount, you can pass an empty array instead of passing any prop or state.

We have already seen how we can replace componentDidMount(), componentDidUpdate() both with useEffect hook. Now we’ll see how we can also replace componentWillUnmount() using useEffect.

To perform any action on component unmount using useEffect hook, the function that is passed to useEffect can return another function that will be executed when the component will unmount. So, whatever we return is a cleanup function.

Data Fetching with useEffect

The UseEffect Hook can also be used for data fetching. Here’s an example where useEffect function uses Axios to fetch the data from the API, after getting the response data, the setData method is called to update the state value.

So far under Effect Hook, we have seen, we can actually replace all lifecycle methods, handle side effects and perform data fetching by using only useEffect function.

This is pretty much in part 1 of React Hooks!!

Let’s summarise what we have seen so far in this part:

- What are React Hooks

- Why it was introduced

- How we can replace class components with functional components using hooks

- useState Hook with examples

- useEffect Hook with examples

I hope this article helped you understand some basic concepts of React Hooks.

In upcoming parts, we’ll talk about:

  • useReducer
  • Reducer vs useReducer
  • Data fetching with useReducer
  • useRef
  • useCallback
  • useMemo
  • useContext
  • Custom Hooks

Stay tuned for upcoming parts!! 😌 👋

--

--

Neha Singh
Globant
Writer for

Web UI developer | Day Dreamer ✨| Night thinker | Love for digital illustrations and doodles ✍️