Reset React State with a Button and Function in our Tic-Tac-Toe Game

Kyle Shevlin
InstructorKyle Shevlin
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

Our tic-tac-toe board works and can be played, but it can't be reset once the game is won or the board is full. Adding this is simple. We'll add another case to our reducer and use a function to regenerate the initialState of our game.

Kyle Shevlin: [0:00] Our game is handling user clicks and filling up, but we currently don't have a way of clearing the board should we want to. This is simple to add with our reducer. We're going to come down here, and we're going to create a function that will dispatch a 'RESET' action to our reducer.

[0:19] We'll use this function inside of a button on our game. When we dispatch({ type: 'RESET' }), we need to handle it, so we'll create a case for that. What we're going to do is we want to return the initialState here.

[0:38] Now, I like to make a small adjustment here. Rather than returning the original object of initialState, I like to get in the habit of returning a function that generates the initialState.

[0:49] The reason is that sometimes in certain games, you might have a function that has some randomized initialState that you want to have, and new calling a function will allow that to happen rather than returning the same reference to object every time.

[1:04] We're going to turn this. Everywhere initialState's used, we're going to call it getInitialState. Then we'll call it, and I will make an adjustment up here. To return an object, we need to wrap it in parentheses. That's an expression. We can save, and our code still works as expected. Now, when we reset, it clears the board for us.

Andy
Andy
~ 2 years ago

I like simple state: https://codereview.stackexchange.com/questions/252111/tic-tac-toe-in-react-official-tutorial/252805#252805 what are your thoughts?

Andy
Andy
~ 2 years ago

Why I did my state different: https://redux.js.org/style-guide/style-guide#keep-state-minimal-and-derive-additional-values

Markdown supported.
Become a member to join the discussionEnroll Today