Menu
Deploy React Application on IIS Server

useState: Managing State in React functional components

Shivangi Rajde 3 years ago 2 18

In this article, we will learn about various hooks introduced in the react’s 16.8 version. React hooks add the ability to manage state and interface with react lifecycle components in functional components.

Hooks let us use state and other React features using functional components. There are several hooks provided by React which we will look around in other articles, in this article we will focus on the basic concepts of hooks and the useState hook.

Introduction

Until now we have used either stateless components or stateful components for creating the react components. There are several things to keep in mind before selecting whether we should use stateless components or stateful components. Generally, we create class components also known as stateful components which help us maintain the local state of our component.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

One of the main benefits of using stateful components over stateless components is that the former allows us to maintain the local state of our component whereas the latter doesn’t. But now after the introduction of Hooks in React’s latest release, stateless components also allow us to maintain the local state of our component using the hooks.

To use the Hooks from the react, we need to import the relevant Hook from the react package as shown:

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

The line above imports the hooks named “useState”. 

The State Hook

The useState hook in React provides similar capabilities as the traditional this.state approach. With the useState hook, we can access the current state value and a corresponding update function to modify the state. It functions similarly to this.setState in class components, allowing us to manage component state in functional components.

Unlike simple numbers or strings, state variables can also hold arrays and objects, making it convenient for organizing related data within a component. By calling useState, we declare a state variable that persists its value between function calls, ensuring that the state is maintained correctly throughout the component’s lifecycle.

Syntax:

Declaring useState hook
const [fruit, setFruit] = useState(); 

This is basically the same as the code below, but we use the array destructuring concept of JavaScript.

const fruitState = useState(‘ ’); 
const fruit = fruitState[0];     //this contains ‘ ’ 
const setFruit = fruitState[1];     //this is a function

The useState hook enables the use of array destructuring with square brackets to assign values. This powerful concept allows for the extraction of values from the useState function’s return, where the first value represents the state variable holding the current value, and the second value represents the update function for modifying the state. By leveraging array destructuring, we can easily assign the state variable and update the function from the useState return values. If you’d like to explore array destructuring in more detail, you can refer to this informative link.

The useState function takes a single parameter, which sets the initial value of the state. In our example, we have an array that contains the state variable “fruit” and the corresponding “setFruit” function responsible for updating the state.

By utilizing the useState hook, you can effectively manage state in your React components while maintaining a clean and concise syntax. When working with hooks in React, initializing the state is straightforward. By passing a parameter to the useState function, we can easily set the initial value of the state variable. Let’s consider the following example:

Assigning default value
const [fruit, setFruit] = useState(‘kiwi’); 

In this case, the state variable “fruit” will be initialized with the value “kiwi”. The useState function takes the provided parameter and sets it as the initial value of the state variable.

On the other hand, in a class component, achieving the same outcome would involve writing additional code, as demonstrated below:

// Class Component
class Example extends React.Component {
    constructor(props) {
       super(props);
       this.state = {
         fruit: 'kiwi',
       };
    }
}

In the class component, we need to define a constructor and use it to set the default value of the state variable “fruit”.

By utilizing hooks, such as useState, we can simplify the process of initializing state in React components, resulting in more concise and readable code.

Rendering the State Value

To render the value of a state variable in a functional component with hooks, you can simply use the state variable directly. Here’s an example:

In this code snippet, the value of the state variable “fruit” is directly rendered within a paragraph tag.

On the other hand, when working with class components in React instead of using hooks, accessing the state variable involves a different syntax. Here’s how it’s done:

<p>Fruit: {this.state.fruit}</p> 

In a class component, we need to use the “this” keyword to access the state variable, followed by the name of the state variable. By understanding how to use state in both functional components with hooks and class components, you can effectively render the state value in your React application.

Updating the State in React Components

To update the state variable in a functional component using hooks, you can call the function provided by useState. This function will set the value of the state variable to the specified parameter. Here’s an example that demonstrates updating the “fruit” variable to “Apple” when a button is clicked:

. . . 
<button onClick={() => setFruit("Apple")}> 
Change Fruit 
</button> 
. . . 

In this code snippet, the onClick event handler is attached to the button. When the button is clicked, the setFruit function is called with the parameter “Apple”, updating the value of the state variable. It’s important to note that in functional components, we don’t use “this” like in class components. Instead, we rely on the useState hook to manage the state.

The equivalent code in a class component would be:

<button onClick={() => this.setState({ fruit: "Apple" })}>
  Change Fruit
</button>

By understanding how to update the state using hooks in functional components, you can easily manage and modify the state variables in your React application.

Click on the link to check the demo for understanding how it works.

Summary

Taking in mind the above example, the useState function returns two values that are similar to “this.state.fruit” and “this.setState” when compared with the class component as that of fruit and setFruit in useState.

To read more about hooks refer to the links given below:
useEffect: The Effect Hook

useTransition Hook

– Advertisement – BuzzMag Ad
Written By

2 Comments

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *