React Hooks : useState
As you know, hooks are new addition in React 16.8. and let you use some React features without writing a class. If you’re not familiar with hooks, I suggest you look into react’s own documentation before reading this article.
In this article, I will talk about useState, one of the most used hooks.
useState is a React Hook that keeps our data between renders. Our Component function is cleaned and computed again on every render. Therefore, when our variables and data are computed again, they return to their initial values. To solve this problem we keep our data with useState.
For better understanding of useState, I want to show a little counter and message app.
useState expects an initial value from us. In contrast with, an array is returned. I get the 0th element of the returned array as count and the 1st element as setCount. While learning the current state value with count, I will update my state with the setCount function.
Here we printed the count value on the screen, and we added the buttons below that allow us to increase or decrease the count value.
We did the same for the message as we did for the counter. Now every time we click the increase button, the counter will increase, and when we click the decrease button, the value will decrease. Also, when we click the change button, the message will change. Let’s see.
As you can see, the state value we hold has changed when we click the buttons. In other words, we assigned a new value to our current state with set functions.
I hope it was a useful article, don’t forget to stay tuned for the continuation of the hooks series.