Introduction To React Hooks

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 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,
  1. import React, { Component } from 'react'      
  2. class MathClass extends Component {      
  3.     constructor(props) {      
  4.         super(props)      
  5.         this.state = {      
  6.             addition: 0      
  7.         }      
  8.         this.incrementValue = this.incrementValue.bind(this)      
  9.     }      
  10.     incrementValue = () => {      
  11.         this.setState({      
  12.             addition: this.state.addition + 1      
  13.         })      
  14.     }      
  15.     render() {      
  16.         return (      
  17.             <div>      
  18.                 <label>Added Value is {this.state.addition}</label><br></br>      
  19.                 <button onClick={this.incrementValue}>Add 1 Value</button>      
  20.             </div>      
  21.         )      
  22.     }      
  23. }    
  24. export default MathClass    
and import this in App.js,
  1. import React from 'react';      
  2. import './App.css';      
  3. import MathClass from './components/MathClass'    
  4. function App() {      
  5.     return (      
  6.         <div className="App">      
  7.             <MathClass></MathClass>      
  8.         </div>      
  9.     );      
  10. }      
  11. 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,
  1. import React,{useState} from 'react'    
  2. function MathFunction() {    
  3.     const[addition,setAddition] = useState(0) // Array Destructuring    
  4.     return (    
  5.         <div>    
  6.             <label>Added Value is {addition}</label><br></br>    
  7.             <button onClick={() => setAddition(addition+1)}>Add 1 Value</button>    
  8.         </div>    
  9.     )    
  10. }      
  11. 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. You can download the source code attached to this article. In the next article we will go in detail about using useState() in ReactJS.
Author
Priyanka Jain
0 9.6k 874.9k
Next » Memo And Refs In React