The state is a kind of instance of the React component class. It can be used to hold information about the component. The data can be changed in the component over time. It is an updatable structure that can be updated while values are changed. Firstly, the state was used with the class component in React. But after the update in React version, React introduced the functional component. So, you cannot manage the state directly in the functional component as in the class component. Hence, React introduced the Hooks concept in React 16.8 version. Mainly, the React hooks are used to play with the React life cycle methods and state. In this post, we will focus on the React useState hook.
If you are an absolute beginner then no need to worry here. I am going to explain to you each and every line of code and terms.
Why React Hook?
The answer is simple and straightforward. When you are creating a functional component then you can’t use the lifecycle methods, state, etc directly. So, React introduced the Hooks for managing state, and using the lifecycle methods in the function-based component. It allows us to hook into the React library while using the functional component. This is easy and convenient to use. It reduces the code length.
How to Create Loading Spinner Using Bootstrap in React JS
What is useState Hooks?
The useState() is a function in the React that is used to manage the state in the functional component. It needs to import along with the React library in the component. We can set the initial value to the state variable. For the state management in functional components, we use react useState hook.
Prerequisites
In terms of a better understanding of React Hooks, I am assuming you are familiar with the following key concepts-
- React Basics
- Class component in React
- State in class component
So, let’s start by creating a new app in React JS. For creating a React JS application, you will require to have the Node.js installed in your system.
Create App in React JS
Open the terminal and hit the below command for creating a new app.
npx create-react-app blog
Here, the React installation has started. So, wait till it completes.
Once the installation has finished, let’s navigate to the app folder and open it in the VS code. Now, run the application to check the installation is successful.
cd blog
npm run start
So, our application is running properly as shown in the result.
File Upload in React JS Using Laravel 8 RESTful API
Create Functional Component in React JS
In the React app, we already have a component named App.js. So, just remove the entire code from the component or you may create a new component. Here, I have created a function in the below snippet to return a simple message.
import React from "react";
import "./App.css";
export const App = () => {
return (
<h4> This is functional component </h4>
);
};
The output will be like this.
Counter Functionality in React JS Using useState Hook
For a better understanding of the useState() hook, I will create a counter functionality. Here, we will have two buttons. One for increment and another for the decrement. When you will click on the increment it will increment the initial value by 1. Similarly, for the decrement, it will decrement the previous value by 1.
But, before applying the useState() hook, I just want to show the benefit of using state. So, let’s see that in the below snippet.
import React from "react";
import "./App.css";
export const App = () => {
let counter = 0;
const increment = () => {
counter++;
console.log(counter);
};
const decrement = () => {
counter--;
console.log(counter);
};
return (
<div className="container">
<h4> Counter {counter} </h4>
<div className="counter-area">
<button onClick={increment}> Increment </button>
<button onClick={decrement}> Decrement </button>
</div>
</div>
);
};
In the above code, I have initialized a variable counter with an initial value. I have added two functions. One for incrementing the counter variable value and another for the decrementing. Also, I have included a CSS file at the top for styling the button and container area for a basic style.
button {
padding: 4px 30px;
margin: 10px !important;
font-size: 20px !important;
height: 50px;
line-height: 30px !important;
border-radius: 4px !important;
border: 1px solid #ccc;
}
button:hover {
opacity: .7;
}
.container {
width: 50%;
margin: 100px auto;
text-align: center;
}
.counter-area {
margin: 40px 0px;
}
Refresh the browser to see the changes.
Here, I have opened the developer console to see the counter value. I have clicked on the increment button two times and the counter value has been increased from 0 to 2.
Also, you may notice the counter value on the UI is still 0. It is not reflecting the value in the DOM.
So, it doesn’t work in the normal way as we had done in the other programming languages. Now, the state comes here. We will need to store the counter value in the state variable then we can display it to the UI.
How to Use Axios in React JS For API Requests Handling
Use of React useState Hook
Before using the useState function, you will need to import the hook along with the React as showing below.
import React, { useState } from "react";
Now, inside the component, just display the log console of the useState() function.
console.log(useState());
In the below result, you can see it returned an array. On the first index, it is something a value that is undefined. And on the second index, it returned a function.
So, the syntax of using useState() hook comes from here.
const [ value, setValue ] = useState();
In the above syntax, we have a const array. This is the array destructuring in JavaScript. The first index (value) is the initial value that we will declare for it. The second index (setValue) is a function that will set the value in the first index dynamically whenever we required.
So, let’s apply it in the counter snippet.
import React, { useState } from "react";
import "./App.css";
export const App = () => {
const [ counter, setCounter ] = useState(0);
const increment = () => {
setCounter(counter+1);
};
const decrement = () => {
setCounter(counter-1);
};
return (
<div className="container">
<h4> Counter {counter} </h4>
<div className="counter-area">
<button onClick={increment}> Increment </button>
<button onClick={decrement}> Decrement </button>
</div>
</div>
);
};
Now refresh the page and try incrementing the value. I have increment the value from 0 to 3 by clicking on the increment button again and again.
In the above result, you can see the value is incremented from 0 to 3 and it is happening in real-time.
Similarly, try decrementing the value. It decremented the value from 3 to 2 and so on.
So, this is the feature of using the useState() hook in React for managing the state.
Form Handling in React JS With Validation Using React State
Conclusion
By using hook in react functional component, you have access to the React life cycle methods. Also, you can use the state without creating a class component. Before introducing the functional component, mainly it was only one way to use state in the class component. But through the same approach, you can write and manage the state in the functional component. So, React hooks enhanced the features in the functional component. I hope, after going through this post, you will have a basic understanding of using the useState hook and managing state in the functional component.
Sam says
Very nice explanation, Thank you.