Transcript
00:00 The objective here is to make it so we don't have to change any of the rest of our code. The stuff that's calling our state updaters, we want to leave that the same. And so we need to implement our reducer in such a way that we preserve this API. Right now it's already using useState and it works just fine. We just need to make sure we don't break it. That's it.
00:18 So let's make our countReducer. And it's going to accept a state and then it's going to accept whatever is passed to the dispatch function, the setCount function. And so what we're passing is actually what we want the new state to be.
00:35 And so we're going to just say state here. It's unknown. We actually don't care. I'm going to just say unknown. And then our second argument, we're going to call it newState. And this will be a number. And then we'll return the new state. So the reason I'm saying the state is unknown is not because I don't know what it is.
00:52 It's going to be a number, but just because I don't care what it is. We're not going to use it anyway. So you feel free to say number here. I don't feel that strongly about that. Okay, great. So now we're doing basically what useState does, is it accepts the new state that we want to have.
01:11 And so we just return that, and that's what our reducer is doing. So we come here and say useReducer. We pass our countReducer and the initial count. We are, of course, going to need to bring in useReducer. And that should get us all set.
01:30 Ta-da! Now we're using useReducer instead of useState. And we're simulating the useState API by accepting whatever the new state should be. And we're just wholesale using that rather than referencing whatever the current state is, because it doesn't make a difference for this particular exercise step.
01:50 But for the future, we are going to be using that. So useReducer, you pass the reducer and then the initial value. You get that initial value on the initial render. When this dispatch function, the setCount function is called, it's going to call our reducer with the current state and the new state,
02:08 and then you combine those two in whatever way you choose to return what the finished state should be. We are just simply returning the new state, returning what we're passed. And that is the first step in your process of understanding this API.