React.js – What is State ?

Hey guys 👋🏻,
In this post, let us cover an introduction to State in React.js.

For this post we will understand✔What is State in React ?✔ Example for creating State in React.✔ Accessing the State✔ Using setState and understanding its pitfall.

✔ Using setState with callback to resolve the pitfall.

pxogniwdxp9s31063jvq-1814934

Introduction to State

Every component manages its own state. With the introduction of React Hooks, you can also use state in functional components. But in this article, we will discuss about state in class components.

Example for creating state :

We define a state property inside the constructor function.

pvxzf6c7l6m8d3vj162r-3809469

To access the state

To access the counter property defined in the state, we can access it in our JSX template by saying
this.state.counter

vue8sajrb2y1tmikvgpt-1219902

DON’T MUTATE THE STATE DIRECTLY, use setState

kht3z3og6s9mycbpxo6d-1118627

But there can be a problem, consider this …

t1lqb2j6oosdsi5tk7mo-8861075

setState does not always immediately update the component. It may batch or defer the update until later. Both the setState calls are enqueued when the value of counter is 0 thus causing the problem.

Let’s solve the above problem.

xgqd3812qxpg28l8hnup-7346107

Use setState with callback because it is guaranteed to fire after the update has been applied. So first counter gets incremented by 1 by first setState call, once it is done, the counter is then incremented to 2. This update is done in a synchronous manner.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

3qpl01uwp1qlmbqkhfpm-7794490

Previous Post
Next Post