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,
- import React, { useState, useEffect } from 'react';
The line above imports the hooks named “useState” and “useEffect”.
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
- const [fruit, setFruit] = useState();
This is basically the same as the code below, but we use array destructuring concept of javaScript.
- const fruitState = useState(‘ ’);
- const fruit = fruitState[0];
- const setFruit = fruitState[1];
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.
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,
- 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”.
- . . .
- Constructor(props){
- Super(props);
- this.state = {
- fruit: ‘kiwi’
- }
- }
- . . .
Using state variable for rendering the value can be as follows,
When using class component in react rather than using react hooks, we generally access the state variable as,
- <p>Fruit: {this.state.fruit}</p>
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.
- . . .
- <button onClick={() => setFruit("Apple")}>
- Change Fruit
- </button>
- . . .
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.
- . . .
- <button onClick={() => this.setState({ fruit: “Apple” }) >
- Change Fruit
- </button>
- . . .
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.
- useEffect(()=>{
-
- return function ( ) {
-
-
- }
- },
- [
- value
- ]
- )
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.
Second parameter as empty array,
- useEffect(() => {
- console.log(`You clicked ${count} times`);
- },
- [ ])
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.
Second parameter with value(s),
- useEffect(() => {
- console.log(`You clicked ${count} times`);
- }, [count]);
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.
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.
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.