What is the useState hook in React JS?

Share your love

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.

Index

What is the useState() hook?

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 –

useState hook

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.

How to declare it?

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( [] );
}

Syntax

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.

Rules for using useState() hook

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 – 

Only call hooks at the top

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.

error message

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.

Only call hooks in React Functions

It is clear from the heading itself that we cannot call hooks inside a class component.

Example time

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,

  1. We have declared useState() hook at the top of our App 
  2. We have declared a variable count with an initial value of ‘0’ – in useState() hook, variables can have any type of value as their initial value, and a function setCount for the updated value.
  3. In this example, we have used both count and setCount. When the user clicks the button, the value of the count will be updated and is now increased by one, this value will be saved in setCount and displayed as the initial value.

Also read: How to apply useState() hook in different cases?

Conclusion

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.

Share your love

2 Comments

Comments are closed.