States in React

In the previous article, we understood how we should think in react, in this article, we will learn how a state works in react, let's start:

Thumb Rule

Initial State, Initial View -> Event -> New State, New View

Syntax for State In React

const [ stateVariable, setterFunction ] = useState();

Let's discuss one problem so that it will be more clear to understand what exactly the state is

We have three buttons Vrushabh, Jayesh & Vaibhav, so whenever we click on Vrushabh it will show "Hi, I'm Vrushabh" & same on clicking on Jayesh as well as the Vaibhav button.

So, here first we identify what is changing, here button name is changing right !

So, first identifying the initial state is very important.

so the code is as below :

const [ name, setName] = useState(" ");

<button onClick={() => setName("Vrushabh")}>Vrushabh</button>

Let's understand the concept, every time we fire any event here button click in React it will run from top to bottom & it will take new value of state & that value of state will come from previous setState function & that is called rerendering.

Rule

Render -> first page initialization Rerender -> After State Change

So, depending upon the state variables, react will adjust its view

So, once we trigger one state & again we triggered the same state then rerendering will not happen as useState() is basically a global variable system in react. So, every time we call setState() function then we say to react like " Hey! something is changed in the state variable then run the whole app which is dependent on that state variable.

Conclusion:

Remember the Golden rule ->

Intial State, Initial View -> Event -> Final State, Final View