Usage of multiple state variables while creating React Component.

Usage of multiple state variables while creating React Component.

Today I will be sharing my learning from my mistake of writing multiple state variables while creating a React component.

Take a look at below code snippet.

tweetCounter (2).png The purpose was to generate a Textbox with a text below counting the number of characters typed until now and the number of characters remaining out of 280 characters tweet limit. As shown in the image below.

tweetCounterMobile.png

But as you see in the image above I have typed the word "React" and it's counting 4 characters instead of 5. So why is there a difference of one character!

The reason for the ambiguity is that setState() does not always immediately update the component. It may batch or defer the update until later.

tweetCounter (1).png

The setter functions don't fire instantly as I assumed here. While the setTextContent(text) creates the new component with the updated new value, our code moves to the next line and still fetches the old value of textContent and not the updated value and sets it to charCount. Thus causing this difference.

The learning from this mistake is that once we set textContent, we should derive all other related values like its length from it, instead of creating a new state variable separately to count its length.

tweetCounter (3).png

As seen in the image now instead of creating charCount as a separate state variable now it's derived directly from textContent. Adding this fix solves our problem.

tweetCounterMobile.png That’s it about this article. Hope you learned something from my mistake today. You can look at the below React Official Doc to learn more about setState.