Working with State in React

Working with State in React with Examples:

In this article, we will discuss the concept of state and why it plays a central role in React applications. Please read our previous article where we discussed How Component Functions are Executed in React with Examples. Here, you will learn how state allows you to store and manage dynamic data within your components, enabling them to respond to user interactions and update their rendering accordingly.

What is State in React?

The state is actually not a React-specific concept but it is a key concept in React as well. In React, “state” refers to an object that stores and manages data within a component. It represents the current state of the component and influences how it renders and behaves. In ExpenseItem.js, we have a scenario where we want to use that built-in state concept. Because the title that changes when the clickHandler executes is actually data that should result in this component being re-evaluated and re-drawn on the screen when that title data changes.

What is State in React?

And by default, regular variables like title, are not triggering such a re-evaluation. React doesn’t care about that. If we have a variable in your component function and those variable changes, react ignores it. It doesn’t care about that. That code executes but the overall component function doesn’t execute again just because some variable changed. And as a side note, even if it would execute again, the title variable would also be recreated and re-initialized to the props value. Because as part of this component function, we are creating this title variable. So even if that would happen, we wouldn’t reach the desired result.

But we don’t even need to think about that because it is not happening. Currently, this ExpenseItem component function is not called a second time after the initial rendering just because a click occurred or because a variable changed does not trigger this component function to run again.

Import multiple things from a library:

So, to tell React that it should run it again, we need to import something from the React library. And we do it by adding a named import.

Import multiple things from a library

The above-shown code is the default import. Here we imported the overall React object. Now, we can add a comma and curly braces and between the curly braces. We can now extract specifically named things from the React library. Now we want to import single pieces from the React library. And we want to import a function here, a function which is called useState.

import React, { useState } from “react”;

‘useState’ is a function provided by the React library and this function allows us to define values as states where changes to these values should reflect in the component function being called again. This is a key difference from the regular variable we’re using here. Now, how do we use this useState function? Well, it’s very simple.

Working with State in React:

Inside of our component function, this is important that we have to do that inside of the function, we just call useState.

Working with State in React

And useState is a React hook. There are other hooks as well, and we are going to learn about all the important hooks later in our articles. But this is one of the most important ones. And all these React hooks can be recognized by the fact that they start with the word “use” in their name, and all these hooks must only be called inside of React component functions like ExpenseItem. They can’t be called outside of these functions. They shouldn’t be called in any nested functions. They must be called directly inside of the component functions. There is one exception which we’ll talk about later but for the moment, that is what you should keep in mind.

Now, the state doesn’t work just like that. Instead, useState once a default state value, because with useState we create a special kind of variable, you can say, a variable where changes will lead this component function to be called again. And of course, we can therefore assign an initial value for that special variable, just as we’re assigning a value for a regular variable. So here, our initial value is props.title. We simply pass props.title as an argument to useState.

useState (props.title);

Working with State in React with Examples

Now the special variable is created. We also want to use that variable. We want to use it in the ExpenseItem.js file. Therefore, useState also returns something. It gives us access to this special variable. However, it does not just return that, it also returns a function that we can then call to assign a new value to that variable. So, we’ll not be assigning values like ‘title = ‘Updated!’’. instead, we will be assigning new values by calling a function. That’s just how this state variable thing works.

And for that useState function returns an array where the first element is the variable itself and the second element is that updating function. We can use a modern JavaScript feature called array destructuring. We can store both elements in separate variables or constants, and here we will use constants. Why it is constant? We will discuss it later.

You can choose any name of your choice because, for array destructuring, it’s just your order that matters. We will name it ‘title’ and ‘setTitle’.

const [title, setTitle] = useState(props.title);

Working with State in React with Examples

As we said, the first element (title) is a pointer at that managed value. So initially at the props.title, the value stored in the props title. And the second element (setTitle) is a function that we can later call to set a new title. Both names are up to you, but the convention is to use something which describes the value. As a name for this first element, since that is the value and then set, and that name is repeated just with a capital starting character. That’s the conventional, how you name these two elements returned by useState.

useState always returns an array with exactly two elements. That’s always the case that the first element is the current state value and the second element is a function for updating that. Now, we can remove that title variable that we created with the let keyword. And we can also remove that value assignment in clickHandler.

State in React with Examples

If we now save everything, we still see Household Expenses there.

State in React with Examples

The button still doesn’t do anything because at the moment we’re not updating the title. Now, as we said, with the value returned by useState, we’re not going to assign a new value with an equal sign. Instead, we assign a new value by calling setTitle and then we just passed a new value as an argument, in this case ‘Updated!!!’.

State in React with Examples

Now, why does it work like this? Why do we have this state updating function instead of assigning a new value with an equal sign? The reason for this is, calling this function will not only assign a new value to some variable, but instead, it is a special variable to begin with. It’s managed by React somewhere in memory. And when we call this state updating function (setTitle), this special variable will not just receive a new value but the component function in which you called the state updating function and in which you initialized your state with useState, will be executed again. And that is exactly what we need.

We want to call the component function (ExpenseItem) again when our state changes. And it will execute again by calling the state updating function. Because by calling the function ‘setTitle’, we’re telling React that we want to assign a new value to this state. And that then also tells React that the component in which the state was registered with useState should be re-evaluated.

And therefore, React will go ahead and execute the ‘ExpenseItem’ component function again, and therefore also evaluate the JSX code again. Then it will draw any changes which it detects compared to the last time evaluation, onto the screen. So, if we now save everything, and click on the “Change Title” button,

State in React

You will see that the title has changed to “Update!!!” for the ExpenseItem where we clicked the button. And that’s how this works. Now you will notice that the console logs still show the title before it was updated. The reason for that is calling the state updating function (setTitle) doesn’t change the value right away, but instead schedules this state update. So, in the very next line thereafter where we console.log, this new value isn’t available. That’s why we see the old value being logged even though we updated it before logging.

State in React

But you see that eventually this component is called again and is evaluated again. And therefore, we see our updated value on the screen. That’s how React state works. This is another key concept in React. If you have data that may change, and changes to that data should be reflected on the user interface, then you need to state. Because a regular variable will not do the trick with state, however, you can set and change values. And when they do change, React will re-evaluate that only component in which the state was registered. Only that component, not any other components, just that component in which this state was registered. Let’s now take a closer look at the state and why we use const. And how everything works in detail.

In the next article, I am going to discuss Working with React useState Hook with Examples. Here, in this article, I try to explain Working with State in React with Examples. I hope you enjoy this Working with State in React article.

Leave a Reply

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