Simple Local State React Counter

Matthew Stahnke
3 min readMay 25, 2021

I’ve seen a lot of blogs that have covered localState but none that I clicked with when I first started learning react. So I’m going to lay everything out in working order then break it down.

Let’s start with the part of the code we can see in the gif above. In the render function between lines 16 — 25. On line 19 is where we are displaying the state of count to the app user. When the corresponding buttons are clicked the count goes up or down respectively. That's fine and dandy but where does count come from on line 19?

In the image on the left lines 4–6 set the initial local state for this component. In our example we only have the default for count set but as seen in the image on the right we can set the state for other variables as well but more on that later.

Back on line 19 we see {this.state.count}. Time to break it down, this is referring to the class because Page is a class Component, state tells the code to look inside the state object that we defined, and then count tells the code to give us the value of count. If we console logged this.state.count by default it would return as 0 and if the state of count were to change the return value would reflect that change as seen in the gif. Now its time look at lines 20 and 21 to see what makes our buttons work. The button is given an event listener onClick={this.addCount} this event listener is told when this button is clicked look for the function inside this class called addCount and then run this function.

It’s important to note that the addCount function is an arrow function. Why? because this is automatically bound for us, other wise we would have to bind this ourselves. On line 9 setState is called on this because we can not manipulate state directly we rely on the built-in setState function. From there we set the count equal to the value of this.state.count + 1. There you have it a functioning counter. Now Let’s look at this in a place that is more common, a like button.

Applying the same idea as count to create a like button is as simple as adding a new value to state, copying the same function changing count likes and finally adding likes value to the label of the button. Well I hope this blog finds a coding student that need a simplified look at state. TTFN

--

--