React's new hooks feature allows you to use state in function components in a really simple and elegant way. Let's look at a very basic example of a <Counter />
component that uses the useState
React hook.
Instructor: [00:00] Here, we have a button that we're rendering with the number zero, and we want to increment this number every time I click on the button. I'm going to extract this, and make a count variable. That count is going to be zero.
[00:12] Then I'm going to import useState from React. This count is actually going to come from a call to useState. Now, useState is going to return an array, and I'm going to destructure that array to get the count out of that array, the first item of the array.
[00:27] Then I'll destructure the setCount function to update that count whenever the button is clicked. We'll add onClick equals this arrow function, to call setCount of count plus one. With that, I now have an incrementing button.
[00:42] Let's go ahead, and we'll just extract this a little bit. We'll call this increment. Increment equals that arrow function, and it still works just as well. In review, to make this work, we used the useState hook from React, and we destructured the array that comes back from that useState hook, which gives us count and setCount.
[01:03] Then we rendered out the count, and then set the onClick handler for the button to increment, which calls setCount for count plus one. Then we could add two. We could also initialize this to four. Now, we're starting at four, and jumping by twos.