React Hooks
Tags: react, javascript, elastikteams
Published: 2021-09-28 05:17:40

 

__React Hooks__

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes.
Hooks are backward-compatible, which means it does not contain any breaking changes. Also, it does not replace your knowledge of React concepts.

__Motivation Behind Hooks__

Hooks solves wide range of problems. Hooks also helps to minimize the complexity of components. One of the most common features any application provides is the states. State is a plain JavaScript object used by React to represent an information about the component's current situation. It's managed in the component (just like any variable declared in a function).
Before Hooks, when we wanted to maintain states, we need to implement class components with state. Maintaining class components with states is always cumbersome process as it requires to write more code, need to remember syntax etc. There is one sentence used in React Documentation 

__*Classes confuse both people and machines*__

We can find when we use class components with states the logic is very much tightly coupled with classes and it is very difficult to reuse the class components, it also not easy to organize the code when we use classes. Classes along with states and other class members requires `“this”`. So, the understanding of this keyword is very important in case of classes. Actually, this keyword is confusing in JavaScript, we have to understand how this works in JavaScript, which is very different from how it works in most languages. There is one disadvantage we have to remember to bind the event handlers.
 
__No Breaking Changes__
Before we continue more on Hooks, please note that-
Hooks are Completely opt-in- We can write hooks in few components without rewriting existing code. 
__100% backwards-compatible__. Hooks don’t contain any breaking changes.

__Why we should opt- in React Hooks__

Before Hooks Functional components only having props. It renders the values from props.
Let’s consider below scenario where we need to print name of the user-

Functional component without using Hooks
```
export function PrintName(props) 
{
    return (
        <div> 
            <h1> Name: {props.name} </h1>
        </div>
     );
}
```

Class Component with Lifecycle method- __componentDidMount__ 
```
import React from 'react';
class PrintName extends React.Component {

    state = {
        names: [],
    };

    async componentDidMount() {
        try {
            const res = await fetch("/api/data");
            this.setState({ names: await res.json() })
        } catch (e) {
            console.error(e);
        }
    }

    render() {
        return <h1> Hello {this.state.names[0]} </h1>;
    }
}
```

Let’s refactor the PrintName component from class to functional component using useEffect Hook
```
import React, { useEffect, useState } from 'react';
function PrintName() {
    const [names, setNames] = useState([]);

    useEffect(() => {
        fetch("/api/data").then(
            res => setNames(res.data)
        )
    }, []);
    
    return (
        <>
            <div>Hello {names[0]}</div>
        </>
    )
}
```
From above example we can see when we use functional components without hooks, they are not able to do much, they just print the values received in props.

When we used the class component, we can see they are more flexible and we can bring dynamic nature by implementing life cycle methods e.g. `componentDidMount`. But we also observed it requires more code to accommodate the dynamic nature into class components. Also, as per our discussion in above section we need to write cumbersome code to maintain state in class components. The changes we made to bring state management and dynamic nature we introduced complexity, also these changes made class component more rigid (we cannot reuse or separate the logic).

Finally, when we refactor the same example with Hook- `useEffect` in functional component we can easily achieved same output with very minimal code changes, without any new complexity.
When to use a Hooks
If you write a functional component, and then you want to add some state to it, previously you do this by converting it into a class. But now you can do it by using a Hook inside the existing function component.

__Rules of Hooks__

Hooks are similar to `JavaScript functions`, but you need to follow these two rules when using them. Hooks rule ensures that all the `state-full` logic in a component is visible in its source code. These rules are:
__1. Only call Hooks at the top level__
Do not call Hooks inside `loops`, `conditions`, or `nested functions`. Hooks should always be used at the `top level` of the React functions. This rule ensures that Hooks are called in the same order each time a component render.
__2. Only call Hooks from React functions__
You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks.

__Pre-requisites for React Hooks__
Node version 6 or above
NPM version 5.2 or above

__Hooks State__
Hook state is the new way of declaring a state in React app. Hook uses `useState` functional component for setting and retrieving state.
__Hooks Effect__
The Effect Hook allows us to perform `side effects` (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to `componentDidMount()`, `componentDidUpdate()`, and `componentWillUnmount()` lifecycle methods.

Side effects have common features which the most web applications need to perform, such as:
Updating the DOM,
Fetching and consuming data from a server API,
Setting up a subscription, etc.
In React component, there are two types of side effects:
Effects Without Cleanup
Effects With Cleanup

__Custom Hooks__
A custom Hook is a JavaScript function. The name of custom Hook starts with `"use"` which can call other Hooks. A custom Hook is just like a regular function, and the word `"use"` in the beginning tells that this function follows the rules of Hooks. Building custom Hooks allows you to extract component logic into reusable functions.

__Built-in Hooks__
Here, we describe the APIs for the built-in Hooks in React. The built-in Hooks can be divided into two parts, which are given below.
__Basic Hooks__
useState
useEffect
useContext
__Additional Hooks__
useReducer
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue

__References__
https://reactjs.org/docs/hooks-intro.html
https://reactjs.org/docs/hooks-overview.html
https://blog.bitsrc.io/6-reasons-to-use-react-hooks-instead-of-classes-7e3ee745fe04