DEV Community

Cover image for React Hooks
Shardul Pathak
Shardul Pathak

Posted on

React Hooks

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>
     );
}
Enter fullscreen mode Exit fullscreen mode

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>;
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (5)

Collapse
 
scriptkavi profile image
ScriptKavi

Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.

Have you started using it?

scriptkavi/hooks

PS: Don't be a late bloomer :P

Collapse
 
ravi8080 profile image
Ravindra Shivdas • Edited

Thank you for providing all the details. This is really helpful.

Collapse
 
paresh4734 profile image
Paresh Awashank

Very useful and explained in detail! thanks!

Collapse
 
meghaghotkar profile image
Megha Ghotkar

This is very useful. Thanks for sharing!

Collapse
 
praneetrane profile image
Praneet Rane

Very detailed, Thanks for sharing!