Current section: State Reducer 30 exercises
solution

Default State Reducer

Loading solution

Transcript

00:00 So we want to get rid of all of this duplicate logic that shows up in our ToggleReducer. So if we go over to the ToggleReducer right here, we're going to export this. And that will allow people to import it and use it directly as they so please.

00:15 So if we come back over here, we can import the ToggleReducer and handle that here. So what if we just delete all of this, this duplicate logic, and we're going to return ToggleReducer from Toggle. There's our state and our action. TypeScript is happy with that.

00:32 And in fact, if we save it right here, then we're able to reuse all of that same logic. Everything is working as it should. And so now we can just add our additional logic on top of that. So we can say if the action type is Toggle and they click too much, then we'll skip calling the ToggleReducer.

00:50 We don't even need to bother calling it. And all is well. And if we wanted to, we could say, hey, actually, like, some things are okay. And so we could actually grab our state, move this up, or I guess we'd call this the new state. Here we go.

01:08 And then we'd say, I'm fine with all of the new state that you would want. But for my state, for the on state, I'm going to have that be the same as it was when it came in. So I'm going to override the new state. Otherwise, we'll return the new state.

01:24 And that also works. It gives us so much control over how we operate our component and or the particular hook, because anytime a state change is going to be made, we can control how that state change happens or if it happens at all.

01:42 This, I think, is a pretty cool pattern. Definitely gives you a lot of power. So there you go. That is the state reducer pattern. Awesome work.