Why we need State variables in react
Tags: react, javascript, frontend, webdev
Published: 2023-08-28 10:45:04

So I got stuck on a very interesting problem today.
Then got to know about `state variables` in react. So I thought I should share what I learnt today.

We will learn about :
- What are State variables ?
- How we can make a state variable ?
- **Why we need state variables ? (mainly we will explore this!!!)**
 
## What are State variables ?

State variables maintain the state of your component.

We can make state variables via useState() Hook. 

> Hooks are JavaScript functions given by React. Period!!!
React has some hooks. Each has some superpowers (logic is written behind the scene).

## How we can make a state variable ?

- First, You will need to import useState() hook like a named import - 

`import { useState } from "react";` 

- Initialize useState
 
`const [A,setA] = useState('Hello world');`

useState() hook returns an array with 2 values.

1. variable which have the respective value(`Hello world` in above case)
2. The function to update the value

Now our state variable `A` has `Hello world` value and via `setA()` method we can change the value `A`.

***_How to change the value via above method ?_***

Simply pass the updated value in function.
`setA('Bye world');`

Now the value of `A` is being updated to `Bye world`.

## Why we need state variables ?

Let's understand with an example here - 

We need to add a toggle functionality i.e. feature of Login/Logout button, If a user is logged out ,then button text should be `Login` and if click on it, text should change to `Logout` and vice versa.

It sounds easy right!!
We can make a variable and store a value in it and on click of the button, change the text.

In below code snippet -
- We made a variable `SessionStatus` and its initial value is `Login`.
- We added a `onClick` handler to change the text accordingly.
- Added a simple logic to change the button text to `Logout` if its value is `Login` and vice versa.

Also added a log statement to check if our onClick handler is getting called and our variable is getting updated or not.
Please try - 

**Code snippet 1**
{% embed https://stackblitz.com/edit/react-q1w9aq?file=src%2FApp.js %}

If you will see in the console, the variable value is changing that means our click Handler is getting called but we are `NOT` able to see the change in button text in our UI.
It's really weird!!!

**_Let's try making `SessionStatus` a state variable and try the same_** 

**Code snippet 2**
{% embed https://stackblitz.com/edit/react-p7mt1t?file=src%2FApp.js %}

Here it is working. Text of button is `ALSO` changing in UI. **_But why ???_**

**State variables syncs UI layer with data layer. Period!!!**
They maintain the state of your component.

Here the value of `state variable` is changing and **when ever state variables changes/updates, React re-renders the whole component** or we can say react reloads the whole component or we can say react calls the component again with the updated values this time.

React does it via **Diff Algorithm**, i.e. calculates the difference between `previous Virtual DOM` and `new Virtual DOM` and then that difference is applied to Actual DOM.
Here only button value is changing, so react re-renders the component again with that change only in the DOM.

> **Virtual DOM** - React keeps a track of UI (the DOM) in memory in the form of object and it is Virtual DOM.


React makes the `DOM operations` superfast.
This is the core of react.


**Here is an interesting observation if you want to understand it one level deep -**

You will observe something weird in code snippet 2. 

Let's say the first time, the text in the button is currently is `Login` and on click, it changes to `Logout` but in console it's value is still printing as `Login`. 
**_Why is that ??_** 
**_We put console.log() after value being updated right ??_
_Then why it does not printed the updated value then and there ??_**

- The answer to this is that `Setting it` does not change the state variable you already have, but instead `triggers a re-render`.
- React will make a `new instance` of state variable with the `new value` in a `new render cycle`. **Period!!!**
- The value which is printing on clicking the button is the value of the variable in the component before the re-render triggered.

Got any doubt or wanna chat? Reach out to me on [linkedIn](https://www.linkedin.com/in/shubham-kant/) or [twitter](https://twitter.com/shubhamkant_).