Hookup of hooks with React!

Vivek Singh
5 min readJul 29, 2021

--

This article is about React Hooks! I just wanted to get a little creative with the title — sorry!

Hooks are a new addition in React 16.8. They let us use state and other important features like lifecycle methods without creating a class i.e. inside a function.

In one of my prod applications which is built on React we were using classes as React Components. With the POCs we did, it was clear to us that using a class based component generated a larger file size while building a deployable file in prod using webpack, when compared to using functional components with hooks. So we started moving towards having a functional component which eventually gave us better performance, more command in code, and easy testability of complex business logic.

So I assume you know this concept of how we create a state inside a class :

Class Test extends React.Component { constructor(props) {
super(props)
this.state = {
counter: 1
}
}
}

So why can’t we do the same thing in a functional component right? — Because in a function component, we have no this, so we can’t assign or read this.state.

function Example() {
this.state = {
count:0;
}
}

This state variable defined above in the function is accessible outside this function as well, while the same state defined in class is not accessible outside the class.

So functional component in React looks like this :

function Example(props) {
// You can use Hooks here!
return <div />;
}

or

const Example = (props) => {
// You can use Hooks here!
return <div />;
}

Earlier we used to name them stateless components, while now with the introduction of hooks we name them functional components.

What is a Hook?

Hooks are nothing but special functions which let you hook/include React features in a function without needing a class.

Why do we need a Hook ? — so that we can hook a state inside a function

We will discuss about two most important hooks here:

  1. useState — helps add a state that can be bound to a functional component

2. useEffect — helps use react lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount

Let’s discuss the above two concepts :

useState

As mentioned earlier in a function component, we have no this, so we can’t assign or read this.state. Hence we need a way to define state inside a function, which we can do using useState hook.

Example :

import React, { useState } from ‘react’;function Example() {
// Declare a new state variable, which we’ll call “count”
const [count, setCount] = useState(0);
return <div>{count}</div>
}

Argument passed — The only argument we pass to a useState is an initial value. If we wanted any more values as state in our function component, we can create more values using useState, meaning we can have multiple useState in a function.

Return — useState returns a pair of values — current state , and a method to update it.

In the above example, we declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.

To read the state value inside a function component :

<p>You clicked {count} times</p>

Notice we do not use this.state.count like we do in a class component.

To update the count value :

<button onClick={() => setCount(count + 1)}>
Click me
</button>

useEffect

To quote React official docs “The Effect Hook lets you perform side effects in function components”. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

Example of useEffect :

import React, { useState, useEffect } from ‘react’;function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

useEffect runs after the first render and after every update. If you want to call an API just after a component is mounted, or you want to do some operations on state change, that can be done inside useEffect. In simpler terms, we can call useEffects when we want to use the life cycle methods of React.

Implementing componentDidMount using hooks

useEffect(() => {
// perform a task
}, []);

useEffect also takes a 2nd argument

To implement componentDidMount() we can pass an empty array []. By doing this, the function passed in useEffect will always run for the first time but for subsequent re-renders it would not re-run as the value of the array is not changing.

Implementing componentDidUpdate using hooks

useEffect(() => {
// perform a task
}, [count]);

With this, useEffect will only execute when the count value changes.

Implementing componentWillUnmount() using Hooks:

useEffect can return a function or cannot . We can return a function from useEffect when we want a task to be executed on an unmount of a function component , meaning the returned function acts as the task to be executed during component unmount.

function Example() {
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id,
handleStatusChange);
// Specify how to clean up after this effect: return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id,
handleStatusChange);
};
});
}

Rules for using hooks :

1.Call hooks at the top level, because hooks are sequential.

2. Use hooks only inside React functional components.

Blog for Custom Hooks

Conclusion

Using hooks we were able to create a prod deployable file with less space, made our code easily testable, and we were able to segregate complex logics written in a component. That being said, class components are not going anywhere, so if the application is really complex then it is better to not invest resources and time in the application to migrate it to use hooks.

Please feel free to reach out to me for any queries or collab . Thanks :)

--

--

Vivek Singh
Vivek Singh

Written by Vivek Singh

Software Developer. I write about Full Stack, NLP and Blockchain. Buy me a coffee - buymeacoffee.com/viveksinless

No responses yet