Current section: useState 16 exercises
solution

Create Your Own useState Generic Function

Transcript

00:00 So the first thing we're going to do is delete useState and now we're going to get some TypeScript errors and all that stuff because we need to have a useState. So let's make a function useState. That's going to take our initial state and what we're going to do is make this a generic function. And so this is going

00:16 to be our state type and that initial state is going to be our state type. And then we are going to have our state which we'll just set to the initial state and our setState will be simply a function. Yeah, we'll actually deal with this later. So our coding assistant is being a little too helpful

00:35 right now. We'll get to that in the next step. Then we'll return the state and set state. And what's interesting is that this is returning an array of either state or a function that returns void. We actually don't want it to do that. We

00:52 want it to return exactly an array where the first item is one thing and the second item is another. So we'll say asConst and that way the count is always going to be the number and setCount is always going to be void. If we don't do that then it says hey count could be a number or the function that

01:09 returns void and setCount can be one of those two things as well. So we're going to add asConst there. Now we're getting a TypeScript error here but I don't need to worry about that right now. If I refresh the page every time I'm going to get that zero, if I click on it nothing happens because we're literally just

01:25 calling this function that doesn't do anything. So that's for a future step. But at this point now we have a useState function that has a similar API to the built-in useState function. It accepts our initial state. It derives that

01:40 state type from whatever is passed in. And so this state is going to be a number. That's what we end up returning because we pass that number to start out. And so the types are all nice and we initialize our state correctly to be whatever the initial state value is that is passed in. So there's the start to our

01:58 useState hook.