In my last post I covered the useEffect Hook. I thought I would continue that theme and cover arguably the most common and important Hook introduced in 16.8, useState. I will touch upon the basics needed to implement the useState hook in your next React application!
useState does just what you think it would: it allows functional components to use and manipulate state. Let’s take a look at an example. In a class component you would creating a state object like so:
With a functional component and useState, the syntax to create state looks a little different:
Here we are creating our state variable “message”, and also establishing a function responsible for changing/setting state which I am calling “setMessage”. useState takes in one argument and that is the initial state value(“hello”). In all, we have created a state variable of message with an initial message of “hello”, and are able to change this message with the setMessage function.
To change our message of hello we need to call our setMessage function. In a class component. We would use setState:
Here, our wave button will call changeMessage when clicked and set our state to “goodbye”. If we wan’t to do this with useState it would like this:
As you can see using useState can be a lot cleaner with less lines of code. On our button we are directly calling our setMessage function which takes in an argument of our new state. Another point I want to highlight is the way we are rendering the state. In class components we call
In functional components we can call our state variable directly like so:
I hope this gave a quick overview of how to use and set state using the useState hook. Again, if you want to delve deeper check out the documentation here.
Happy Holidays Everyone!