Current section: Advanced State Management 36 exercises
Problem

Real World

Loading exercise

Transcript

00:00 All right, let's make this a little bit more real world. This might be familiar to you, and in fact, you might even have a game that was saved in local storage that loaded up when you loaded this playground up, like it did for me. But yeah, we're going to be taking the tic-tac-toe game and using useReducer for it instead.

00:19 We're going to have a couple different game actions, so you can select a square or a step and restart, and those carry along with it the data that they need. We'll have a gameReducer that handles all of the logic of our game. But there's something else that we're going to be doing that's a little bit different, which is a lazy initializer for the reducer.

00:39 So you might recall for useState, that useState call can be passed to the initial state, or it can be passed to a function that is then called to return an initial state. And that's what we did for this game, because we're reading local storage and parsing with JSON and all this stuff.

00:54 So we need to do that for our useReducer situation here as well, and useReducer is a little bit different. So useReducer before, we had our reducer and then we had our initial value. Now we're going to have our reducer, and then we're going to have an argument that

01:13 goes into the function that we use to determine our initial value. So that second, when you have three arguments that you're passing to useReducer, then the second one is actually just an argument that goes into the third one. That's what's going on right there.

01:30 So your job is to implement this game as a reducer, you're refactoring from useState to useReducer, moving all the logic into your gameReducer, and then make sure that you handle the lazy initialization with useReducer, which is a little different from useState. Okay, I think you're ready. Let's get going.