How to reload a page (state) in a react app

I like solution in the article with keeping previous state and reset function - https://medium.com/@justintulk/best-practices-for-resetting-an-es6-react-components-state-81c0c86df98d

In Constructor:

// preserve the initial state in a new object
this.baseState = this.state 

and

resetForm = () => {
  this.setState(this.baseState)
}

Check the code snippet below for workaround for the refreshing page in order to reset the game.

But this is not the best practice since React support changing the state which makes (by default) the component re-render. React has the concept called Virtual DOM. so that the app will be pretty fast. Because React will update the actual DOM by comparing diff.

It is best to change the state as other answers suggested. this.setState({games:[]})

Below is the code snippet for workaround(refreshing page)

class App extends React.Component {
    render() {
      return ( < button onClick = {this._refreshPage} > test </button>);
      }

      _refreshPage() {
        console.log("Clicked");
        window.location.reload();
      }
    }


ReactDOM.render( < App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id="app"></div>

There are 2 ways to

  • either you can reset the Game by resetting state
  • You can reload the web page and reset the react application.

Second one has its reason but bit costly as well.

way 1 - Refering to @bennygel answer

  // add a method to your component for resetting state
restartGame(event) {
  this.setState({ games: [] });
}

// and in your components render or any other place add the reset button

<button type="button" onClick={ this.restartGame.bind(this) }>
  <span>Reload</span>
</button>

way 2 : Refering to @dwij answer


In react you don't have to refresh page to reset state. I looked at your project and saw that you are holding your scores and game data in component's state. This helps you to reset game easily with just setting the state to the initial values.

For Example

// add a method to your component for resetting state
restartGame(event) {
  this.setState({ games: [] });
}

// and in your components render or any other place add the reset button
<button type="button" onClick={ this.restartGame.bind(this) }>
  <span>Reload</span>
</button>

Don't forget to bind your methods to be able to use this in them. For more information about that you can read react documentation for Handling Events.