React Hooks: useState – Part 2

Use State React Hook
Reading Time: 3 minutes

As we can discuss a lot about React Hooks in React Hooks: Introduction – Part 1. In this blog, we are going to discuss the useState hook in detail. As this hook let us use state without writing a class. This hook is the equivalent of this.state/this.setState for functional components.

Declaring a state variable

useState is a named export from react so to use it, write:

React.useState

or to import it, write:

import React, { useState } from 'react';

A state object declared in a class allows you to declare more than one state variable.

import React from 'react';

class Knoldus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      count: 0,
      isModalOpen: false
    };
  }
}

But useState hook allows you to declare only one state variable at a time.

import React, { useState } from 'react';

const Knoldus = () => {
  const [name, setName] = useState('');
  const [count, setCount] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
}

Let’s discuss the above example in detail:

  1. useState declares a state variable. It is a new way to use the exact same capabilities that this.state in class-based components.
  2. The only argument to the useState is the initial value for the state variable. We can keep a number, string, or any value that we need as the initial value. Using useState alone won’t work because its arguments are used the first time only – not every time the property changes. In our example, we just want the initial value of
    • name as an empty string
    • count to be 0
    • isModalOpen to false.
  3. useState returns an array, where the first element is the state variable and the second element is a function to update the value of that variable. Usually, we will use the array destructuring to simplify the state variable declaration.
    This is why we write const [name, setName] = useState(”) . This is is similar to this.state.name and this.setState in a class-based component.

Reading State Variable

In class-based component, we can use state variable:

<p>Name: {this.state.name}</p>
<p>Total Count: {this.state.count}</p>
<p>Is modal open: {this.state.isModalOpen}</p>

In a functional component, we can use state variable directly:

<p>Name: {name}</p>
<p>Total Count: {count}</p>
<p>Is modal open: {isModalOpen}</p>

Updating State Variable

In class-based component, we need to call this.setState to update the state:

<button onClick={() => this.setState({
  ...state, 
  isModalOpen: false
})}>
  Close Modal
</button>

But in functional component, we already have a setIsModalOpen function to close the modal:

<button onClick={() => setIsModalOpen(false)}>
  Close Modal
</button>

Similiarly, setName and setCount are used to update the values of their respective state variables.

Rules for using the useState Hook

useState follows the same rules that all hooks follow:

  • Only call useState at the top level.
  • Only call useState in functional components.

The first rule means you should not call useState in loops, conditions, or nested functions, even inside functional components, because React relies on the order in which useState functions are called to get the correct value.

if (condition) {
  const [name, setName] = useState( '' );
  setName( 'Rudar' );  
}

The second rule is easy to follow. Don’t use useState in a class based components.

import React, { Component, useState } from 'react';

class App extends Component {
  render() {
    const [name, setName] = useState( '' );

    return (
      <p>Name: {name}</p>
    )
  }
}

If you are violating this rule you will get an error.

Further in the series, we will discuss various hooks in detail.

For more details, visit React Docs.

Knoldus Footer

Written by 

Rudar Daman Singla is the Trainee Software Consultant at Knoldus Software LLP. He has done B.Tech. from Jaypee University of Information technology, Waknaghat(Solan). He has good knowledge of languages C, C++, Java, Scala, HTML, CSS, PHP, Node and Angular. He is also interested in VFX. As a fresher, he always tries to explore the different type of software and tools.