An in-depth guide on State in React

An in-depth guide on State in React

In this article, we will be discussing on the State, how to declare it, how it works and when to use it. Also, some problems in state.

Introduction:

In React, State is one of the essential concepts to learn. If you are new to React or an intermediate-level developer, this article will help you to dive deep into State and help you to write better code. Here we are discussing component-based State and the useState() hook.

What is State?

State is where you can store the property values that belong to the component. Every time a state is changed, the component re-renders itself. We can define a state using the useState() hook in React. The steps to define a simple state are:

  1. import useState hook from react.

  2. Inside the component function, define a state variable. Here you need to use array destructuring to define the state. The first value is the name of the state variable. The second one is the state setter function. We normally put ‘set’ before the state name to define the function name here. And inside the useState braces, you can put the initial value of the state variable.

  3. Inside the JSX code, to update the state value use the state setter function to update the value. Here is a simple example to define a state:

import { useState } from 'react';

const App = () => {
    const [greeting, setGreeting] = useState("");
    return ( 
        <div>
            <button onClick={() => {setGreeting('Hi there!')}}>
                Show Greetings
            </button>
            <h1>The message is: {greeting} </h1>
        </div>
}

export default App;

When to use it?

After learning about the state, it is common behaviour to use the state for everything. But you need to know where to use it and where not. If you want to re-evaluate your HTML or re-render some components after any value change, then the state will be a perfect choice for you. But you just want to store and render some value and they didn’t update on the component life cycle, then use a normal variable.

How state works?

In React, state updates are asynchronous. It means if you want to access a state value just after calling its state updating function that will not give you the new value. Whenever React updates a state, it will re-evaluate the whole component and checks the value which needs to be updated. After updating the state it will generate a new virtual DOM and compare it will the actual DOM. Then it will find the HTML element which needs to be updated in the actual DOM and just re-renders that particular HTML element, not the whole DOM.

A better way to update the state

In React, state updates have some problems. If your new state value is dependent on the previous state then it will make an issue. Let’s say you have a count state with an initial value of 0. After clicking on a button it will call the state update function twice with count+1 as the new value. Now what do you expect? As you call the setCount method twice so it should give you 2 when clicking on the button. But the actual output is 1.

import { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);
    const incrementHandler = () => {
        setCount(count+1); 
        setCount(count+1);
    }
    return (     
        <div>
            <h1>{count}</hi>
            <button onClick={incrementHandler}>Increment by 2</button>           
        </div>
    )
}

export default Counter;

Then, how to get the new value of the state. It is happening because state updates are asynchronous in React. To resolve this there is another syntax available. If your new state value is dependent on the previous state value, then this syntax will be very useful. Here we pass a callback function inside the setCount function. This callback always gets the previous state as a parameter and based on the previous state we can update the new state value. With this syntax, if you write the code it will give you 2, not 1.

import { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);
    const incrementHandler = ( ) => {
        setCount((prevCount) => prevCount + 1); 
        setCount((prevCount) => prevCount + 1);
    }
    return ( 
        <div>
            <h1>{count}</h1>
            <button onClick={incrementHandler}>Increment by 2</button>         
        </div>
    )
}

export default Counter;

Summary

In this article, we discussed the state, how to declare it, how it works and when to use it. Also, some of the potential problems in state updates. In React, state is one of the most important concepts.