Functional Components are the talk of the world now when it comes to coding in React. There are various reasons for that, but the main reason is that it makes writing code easier, cleaner, and more understandable.
But, this only became possible after the introduction of hooks in React Version 16.8, as now developers can use Functional Components for lifecycle and state management purposes too.
In this version, there are many hooks, but only two of them are widely used – useState() hook and useEffect() hook.
This blog is focused on understanding the useState hook for functional components with pretty simple examples.
Before understanding the main concept, let’s first understand what is state. Any data that defines an application’s actions is referred to as “state.” If we wanted to, we might categorize it as “server state,” “communications state,” or “location state,” but the point is that data is being processed, read, modified, and used.
According to the official documentation, “useState is a Hook that lets us add React state to function components”. It simply means that we can now declare state variables to functional components.
This hook has made declaring a state in our function easier as we don’t have to convert it into a class before declaring as with Class Components and we can even use it directly in the function.
Let’s understand this with an example –
In the above image, we have compared both Functional Components and Class Components ways of declaring and managing a state through an example.
It should be clear that the hooks have made declaring and managing states inside the function easy and without any prefixes – this.
The state declared in a Class Component will always be an object, while the state declared in the Functional Components can be an object, array, boolean, or any other data type we want it to be. With this only, useState() has proven that there are endless possibilities of declaring and managing a state with them.
Well, there are many ways in which we can declare useState() hook, but the common one among them is declaring it at the top of our App like this –
import React, { useState } from "react";
You can read this article if we want to learn about the other ways in which we can declare useState() in our App
According to the official documentation, “declaring a state variable is a way to preserve some values between the functional calls so that it can be used again”.
What it means is – in JavaScript, the variable declared by const is block-scoped, and its value can only be used inside curly braces, but it’s different in the case of React. In React the values are preserved and can be used anywhere in the App
This is only possible because we are passing those values as props to other components.
Can we store two different values in our App? – Unlike the Class Components, where we can declare more than one state variable each for a different value, the useState() hook can only be declared once per component, but it can be called as many times as possible as shown –
import React, { useState } from 'react';
const Message= () => {
const messageState = useState( '' );
const listState = useState( [] );
}
Its syntax consists of two elements which can be called anything – in this case, its count and setCount
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(initial value);
The first value will contain the initial value -no matter its type like this.state.count, while the second value is a function that will always return the updated state like this.setState in Class Components, and the square brackets in the above syntax symbolize array destructuring.
Every hook introduced with React v.16.8 has to follow a certain set of rules, and useState() is no exception.
There are just two rules that every hook, even those we make, have to follow –
According to it, hooks should only be called at the top of the function so that they can re-render with the component.
Calling hooks anywhere else except at the top of the function will give us an error. The below image will make this statement clear to you.
According to the error message, hooks can’t be called in a condition statement. It also cannot be called in a loop and even be called in a nested statement. They are always called at the top of the function.
The second states that hooks must be called in an order, which we have already discussed in our previous blog which you can read here.
That’s what allows React to preserve the state between every re-render.
It is clear from the heading itself that we cannot call hooks inside a class component.
We have theoretically understood the useState() hook, and now it’s time to understand it through an example
import React from "react";
const Count = () => {
const [count, setCount] = useState(0);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>10: Click me 11: </button>
</>
);
};
export default Count;
Above is the code we have seen since the beginning of this blog, the Counter App. This App increases the value by 1 when the button is clicked.
Let’s have a recap of what we have learned in this blog,
Also read: How to apply useState() hook in different cases?
useState() is a hook that lets us declare state variables in a pair of functional components. This pair contains a variable that stores the initial value of the state and a function that stores the updated value of the state and React does a nice job of remembering these values and displays the current value when told to do so.
Inheritance in Java is a mechanism of creating a new class or interface from an…
In this blog, we will not only understand the concepts of OOPS in Java in…
Object-Oriented Programming System (OOPS) is a programming paradigm built around the concept of objects —…
Abstraction in Java is one of the four pillars of OOPs which is used to…
In this blog, we will learn How to Detect a Click Outside of a React…
learn How to Use Hooks to Create Infinite Scrolling in React by making a custom…