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.
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.
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
DON’T MUTATE THE STATE DIRECTLY, use setState
But there can be a problem, consider this …
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.
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.