Introduction to Hooks in ReactJs

Introduction

In the previous series, we learned about the basics of ReactJS in which we have gone through the concept of Props and State, Functional and Class Component, Portal and Boundaries, Fragments and Pure Components. 

In this series, we are going one step ahead. We are going to learn about the concept of Hooks and why Hooks are required. 

What are Hooks?

Hooks are an additional feature added in React version 16.8. It is the first release of React that supports hooks. Hooks allow us to use state and other React features without writing a class. 

Why are Hooks required?

There are numerous issues that existed before the release of hooks. Some of them are,

  • Use of this keyword is a must while using class component. And it is a bit different from JavaScript, so hooks provide a way to get rid of “this” keyword.
  • While using class component, we need to remember to bind event handlers but that is not the case with hooks.
  • While using class component, classes cannot be minified very well and don’t have reliable reloading.
  • Stateful component logic has no way to reuse its component.
  • Using a class component makes code hard to follow and maintain changes.
  • While using class component complex scenarios such as data fetching, animation or event handlers do not include organizing code in one place. This is due to implementing logic in lifecycle methods. Like Data retrieval, the process should be included in componentDidMount() and componentDidUpdate() methods. Due to this reason sometimes, code cannot be broken into small components

The above problems can be resolved using hooks, hooks provide a better way to implement logic, make smaller code fragments and provide more reusability. Hooks can be implemented only in functional component they cannot be implemented the in-class component. 

Important Point to remember while using Hooks

  1. Your application must have React version 16.8 or higher
  2. Hooks must be used within a functional component cannot be used within a class component.
  3. Hooks are completely optional, there is no compulsion for using Hooks.
  4. It is not required to remove class while using Hooks as Hooks cannot be implemented within a class component, but it can communicate with class component.
  5. Hooks are completely backward compatible, it does not involve any breaking changes.
  6. Hooks can be implemented within an existing application without breaking the application.
  7. Hooks do not require any new knowledge of React, It will reuse existing knowledge such as props, State, etc. Hooks also provide direct API to use existing React knowledge.

useState() Hook

This is the first Basic hook of ReactJs. This hook is a replacement of state which is done in class components. Just like we cannot use this.setState() in functional component in the same way we cannot use useState() hooks in functional components. 

useState() provides us a way to manage state when a functional component is used. 

Syntax,

const[state, setState] = useState(initialState)

The useState returns a stateful value and a function to update it. Let see an example, First, we will create a class component that will increase value by 1 on click of a button. 

Add new component MathClass.js,

import React, { Component } from 'react'      
class MathClass extends Component {      
    constructor(props) {      
        super(props)      
        this.state = {      
            addition: 0      
        }      
        this.incrementValue = this.incrementValue.bind(this)      
    }      
    incrementValue = () => {      
        this.setState({      
            addition: this.state.addition + 1      
        })      
    }      
    render() {      
        return (      
            <div>      
                <label>Added Value is {this.state.addition}</label><br></br>      
                <button onClick={this.incrementValue}>Add 1 Value</button>      
            </div>      
        )      
    }      
}    
export default MathClass

and import this in App.js,

import React from 'react';      
import './App.css';      
import MathClass from './components/MathClass'    
function App() {      
    return (      
        <div className="App">      
            <MathClass></MathClass>      
        </div>      
    );      
}      
export default App;

This will display output as below,

On button click, it will display as,

Now we will create the same example with the help of functional component having the name as MathFunction.js,

import React,{useState} from 'react'    
function MathFunction() {    
    const[addition,setAddition] = useState(0) // Array Destructuring    
    return (    
        <div>    
            <label>Added Value is {addition}</label><br></br>    
            <button onClick={() => setAddition(addition+1)}>Add 1 Value</button>    
        </div>    
    )    
}      
export default MathFunction   

The output will be displayed as below,

There are 3 steps to implement your addition function or class,

  1. Create a component (functional or class).
  2. Need a state property that needs to be initialized
  3. Require a method that will set up state property

Rules of Hooks 

 There are 2 important rules for using Hooks,

  1. Hooks should only be called at Top-level; Hooks should not be used within loops, conditions and nested function.
  2. React hooks should only be called from functional components. It should not be used within any regular JavaScript functions.

Summary

In this article, we have learned about what hooks are, why hooks are used, and how they can be implemented. In the next article we will go in detail about using useState() in ReactJS.

Any question or feedback or suggestion, please do comment and let me know.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s