Learn About React Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
 
Until now we have used either stateless component or stateful components for creating the react components. There are several things to keep in mind before selecting whether we should use stateless components or stateful components.Generally, we create class components also known as stateful components which help us maintain the local state our component.
 
One of the main benefits of using stateful components over stateless components is that the former allows us to maintain the local state of our component whereas later doesn’t. But now after the introduction of Hooks in React's latest release, stateless components also allow us to maintain the local state of our component using the hooks.
 
To use the Hooks from the react, we need to import the relevant Hook from the react package as shown,
  1. import React, { useState, useEffect } from 'react';    
The line above imports the hooks named “useState” and “useEffect”. 
 

The State Hook

 
useState gives us capabilities same as of this.state.The state hook provides us the value of current state and a function which will be used for updating that state. When comparing it with the class component which we used till now, the state hook functions similar to this.setState in the class component.
 
The state variables not only hold numbers or strings, they can also hold arrays and objects so that it would be handy to group related data.
 
Calling useState declares the state variable which helps us preserving the values between function calls.
 
Syntax
  1. const [fruit, setFruit] = useState();    
This is basically the same as the code below, but we use array destructuring concept of javaScript.
  1. const fruitState = useState(‘ ’);       
  2. const fruit = fruitState[0];     //this contains ‘ ’     
  3. const setFruit = fruitState[1];     //this is a function     
Here, square brackets are used by using the concept of “array destructuring”. Now, what does that mean? In simple words the value from the useState (right-hand side) will have two values to return, from which the first value on the left-hand side will be assigned as the state variable consisting of current value and the second value on the right-hand side will be assigned to the function for updating the state. For more information on array destructuring you can refer this link
 
Here, we have an array which has the state variable I.e. “fruit” and the function “setFruit” that will be used to update the state. useStateonly has one parameter to be passed, which sets the initial value of the state.
 

Initializing the state

 
Using hooks, we just need to pass a parameter to set the initial value of the state variable. It can be done as shown in below example,
  1. const [fruit, setFruit] = useState(‘kiwi’);   
The state variable will be initialized by the value “kiwi”, as the parameter provided to the useState function sets the initial value of the state variable.
 
Whereas, the same thing when done in class component looks something like,
 
This line is equivalent to code given below when using class component in react. The line simply sets the default value of the state “fruit”.
  1. . . .     
  2. Constructor(props){     
  3.    Super(props);     
  4.    this.state = {     
  5.       fruit: ‘kiwi’     
  6.    }     
  7. }     
  8. . . .     
Using the state
 
Using state variable for rendering the value can be as follows,
  1. <p>Fruit: {fruit}</p>     
When using class component in react rather than using react hooks, we generally access the state variable as,
  1. <p>Fruit: {this.state.fruit}</p>   
Updating the state
 
The function provided in useState can be called as a function from an event handler or somewhere else. The example below will set the value of state variable to the value provided as parameter in the function. For example, here setFruit function sets the value of the “fruit” variable to “Apple” when the button is clicked.
  1. . . .     
  2. <button onClick={() => setFruit("Apple")}>     
  3.    Change Fruit     
  4. </button>     
  5. . . .      
We cannot use “this” in functional components, so if we need to setState then we need to use useState in our component.
 
The “setFruit” function is equivalent to the lines below when using class component in react.
  1. . . .     
  2. <button onClick={() => this.setState({ fruit: “Apple” }) >     
  3.    Change Fruit     
  4. </button>     
  5. . . .      

The Effect Hook

 
The effect hook is used to provide effects to our functional components. As compared to class component the effect of the Effect hook will be the same as of the componentDidMount, componentWillMount and shouldComponentUpdate.
  1. useEffect(()=>{       
  2. //called on every re-render. Called on component update, mount and unmount       
  3.    return function ( ) {       
  4.       //called when the component unmounts       
  5.       //used for clean-up       
  6.    }       
  7. },       
  8.    [                //second Parameter       
  9.       value         //monitored value       
  10.    ]       
  11. )      
Second parameter is passed for conditional rendering. To understand that there are few scenarios which tell us the possible ways to use that.
 
There are multiple scenarios which will make it easier for you to understand the importance and functionality of the second parameter with the help of the example from demo.
 
Scenario 1
 
Second parameter as empty array,
  1. useEffect(() => {     
  2.     console.log(`You clicked ${count} times`);     
  3.   },      
  4. [ ])            //called only once similar to componentDidMount     
If we pass an empty array, it means that we are not interested in monitoring any of the values so that the useEffect won’t be called except on mounting and before unmounting.This mimic’s the working of componentDidMount and componentWillUnmount, it will only run once.
 
Scenario 2
 
Second parameter with value(s),
  1. useEffect(() => {     
  2.    console.log(`You clicked ${count} times`);     
  3. }, [count]);      //function inside useEffect will be called when "count" will be updated     
The value passed as the second parameter (array) here in our example: countwill be responsible for the execution of the function inside the useEffect Hook. If the value inside the array will be updated, then and only then the function will be executed.
 
What if we have multiple useEffect hooks and we need to update just few of them? Conditional rendering comes in light. Conditional rendering is achieved by passing the secondparameter instead of just empty array. The values in the array will be monitored and the useEffectfunctionwill only be called when the monitored value(s) is/are updated.
 

Possible errors

 
There are some problems which may occur, for example your program will go to an infinite loop as our useEffect hook doesn’t monitor any value(s). This condition can occur if we don’t pass the second argument and set the state variable inside the useEffect hook. This happens as at the time of rendering useEffect will be called and when the function will be executed set function of useState will be called inside it, so this scenario will lead to infinite loop.
 

Summary

 
Taking in mind the above example, the useState function returns two values which are similar to “this.state.fruit” and “this.setState” when compared with class component as that of fruit and setFruit in useState.
 
Actions to be performed include  calling an API, setting localStorage or making any changes to the DOM component.