Table of contents
1.
Introduction:
2.
Need for hooks:
3.
Function Components:
4.
Introducing a Hook:
5.
Declaration of state variable:
5.1.
Using useState as an argument
5.2.
What useState returns?
6.
Reading state
7.
State update
8.
Short notes
9.
Frequently asked questions:
10.
Key Takeaways:
Last Updated: Mar 27, 2024

Using the state hook

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction:

Before proceeding ahead, the first thing which comes to our mind is what exactly this hook is? As the name suggests, hooks connect and help to use state and other react features without writing a class. Hooks cannot work inside classes. Rather, they can be used instead of writing classes. Confusing right!!. 

Let’s figure it out in a bit of detail.

Let’s start the discussion with an example. The below code snippet contains a simple class in react.

Also See, Dropdown in React JS

Need for hooks:

The state starts with a ‘counter’ initialized to 0, state. Counter gets incremented, the user clicks the button in this.setstate().  The counter here helps to concentrate on the API; even we are working with the hooks.

class Example extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      counter: 0

    };

  }

 

  render() {

    return (

      <div>

        <p>click operation {this.state.counter} times</p>

        <button onClick={() => this.setState({ counter: this.state.counter + 1 })}>

          Clicking oparation

        </button>

      </div>

    );

  }

}

export default Example;

 

Output:

 

Function Components:

Function component in react generally looks like:

const Helper= (props) => {

  //Hooks can be used here!

  return <div />;

}

 

Or,

function Helper(props) {

  // You can use Hooks here!

  return <div />;

}

 

From the examples given above, previously, they are considered as “stateless components.” In this blog, we will learn how to use react states with these components so that we will refer to them as “function components.” 

Introducing a Hook:

A hook is a unique function that lets you get a grip or “hook into” react features. Using hooks, react features can be used directly even without classes. Let’s look into an example; the useState hook allows to add react state of functioning components. 

When should I use hooks?

Consider a situation when you start writing a function component, and you have come a long way. The program is about to be complete, but you realize that you need to add some state to it. For doing so, previously redeclaration of it in class is required. 

But using hooks, you can declare it inside the function component. Let’s catch an example of this; things will be crystal clear then. 

Declaration of state variable:

Generally in class, we use this to initialize any counter. In the example below, we have initialised the counter state to 0, by setting this.state to 0{ count: 0 } in the constructor:

class Example extends React.Component {

  constructor(props) {

    super(props);

   this.state = {

     counter: 0

   };

 }

 

Instead in the function component, there is no this. We can’t assign values to this.state. We can directly refer to the useState hook inside the component and do the needful changes. 

This useState at first declares a “state variable.” Here, in the above code, “counter” is the name of the variable. We can use anything in the name of a variable like “apple” also. Using the counter, some values can be stored in between the function calls. useState does the same work as this.state does in case of a class. If any function exists, the variables disappear but react to preserve the state variables.

Using useState as an argument

The initial state is the only argument to useState hook. Unlike classes, this hook doesn’t need objects. If required, a string or a number can be kept. 

What useState returns?

useState returns two things: the current state and a function that updates it. Correct syntax to write is const [count, setCount] = useState(). In class, the similar operation is performed by this.state.count and this.setState. 

import React, { useState } from 'react';

function Helper() {

 // Declare a new state variable, which we'll call "count"
 const [count, setCount] = useState(0);

 

In the example given above, a state variable “count” is declared and initialized to zero. React will maintain all the values between its re-renders and will retain its current value. The most recent value is provided to the function. For updating the current count, call setCount

Reading state

For displaying current count in a class, we use this.state.count. Below is the example:

 <pUser Clicked {this.state.count} times</p>

 

But, in a function, count can be used directly. The below example shows that how in a function, the counter can be used directly.

<p> User clicked {count} times </p>

 

State update

For updating in a class, call this.setState() and update the counter count state. 

<button onClick={() => this.setState({ count: this.state.count + 1 })}>

   Hit me

</button>

 

But in a function, we already have setCount and count as variables declared, so we don’t need this:

<button onClick={() => setCount(count + 1)}>

  Hit me

</button>

 

Short notes

For better understanding, let’s take an example:

import React, { useState } from 'react';
 function Helper() {

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>User clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>
        Clike here
      </button>
    </div>
  );
}
export default Helper;

 

Output:

 

  • In the first line, the useState hook is imported from react. This hook lets you keep the local components in the function component. 
  • In line 4, a new state variable is declared by calling useState hook. The variable “count” maintains the number of times the button is clicked. The counter is initialized to zero as the only useState argument. Another function is the setCount which returns the changed value of the count variable.
  • In line 9, when the button is clicked, setCount is called with a new value. Then react will again re-render the helper function component with the latest count value to it.

Frequently asked questions:

 

  1. What does useState hook do?
    useState hook is a unique function that takes the initial state as an argument and returns the updated entries.
     
  2. What are hooks in React JS?
    Hooks are the special kind of functions that allow hook-up or use the react state and function lifecycle features. Hooks cannot work inside classes.
     
  3. Is it possible to use a hook inside a hook?
    No, it’s not possible to use a hook inside a hook. Doing so will violate the rule of Hooks which states that no two hooks can be initialized one within another.

 

Key Takeaways:

In this blog, we have learned about another hook provided by react called useState. It is also known as “state hook.” Using this, we can add local state to react function components. This is the most exciting part, which we learned for the very first time. 

We have also looked towards what exactly hooks are; one of the most interesting things to notice is Hooks names always start with “use.” 

Keeping the theoretical knowledge at our fingertips helps us get about half the work done. To gain complete understanding, practice is a must. To gain complete understanding, visit our page.

~ happy learning

By: Pradipta Choudhury

Live masterclass