React hooks are something that are very important when writing any type front end code using… well… react, so here I am today to try and explain in my own english words what is useState and why is it important? useState is a hook that lets a developer add state to a functional component according to a stack overflow answer. How I see it is that it lets you add state to a function component, as in a person is stuffing a turkey with stuffing, a developer is inserting state into a function component. Not the best analogy but its something that I assume most people have done.
With the code that will be presented today, it will be a counter using react and a function called app that will return two buttons and an integer.
This is what would be shown with the code written above, if you were to open a new file and create a react application and put in the same code, the result would be what is above. Nothing will happen just yet if you decide to increase or decrease when pressing the buttons. This is where we are going to start inserting useState.
Now with using const on two arrays, we are actually using both in just a moment, but let’s talk about count within the array for now. So what is being done within useState is that where the integer of 0 used to be is going to be replaced with whatever is within the useState, which in this case is 3. Following up, we will now add a decrease count function to be able to lower it, which is very simple, we can name a function whatever we want and have it set to setCount which is the second variable within the array and have the argument hold count — 1. We then give onClick to both buttons the correct functions that correlate what we would like to do. (I’ve decided to create an echo version of decrease count by making an increase one).
With doing that, we can now increase or decrease our counter by 1! This was the most simplistic way of showing what use state can do with a tiny bit of code. To sum it all up, useState is a hook thats used for many things to be done immediately to update the state! As shown here we just used it as a counter, increasing or decreasing an integer by 1! We could always add more or update it to where we can have it set to 3 increases per click and 2 per decrease click! Thank you once again for stopping by and letting try my best to explain code! I’ll see ya when you get older!