I'm not certain whether I'm phrasing the question right, but essentially I was following a tutorial where we needed a way to reset the state of a react class component to its initial state. I went ahead and implemented it by creating an object with initial values, and setting the component state to equal it:
// My implementation *****************************************
class Game extends React.Component {
// store the initial state of the game
static initialState = {
selectedNumbers: [],
numberOfStars: Game.randomNumber(),
answerIsCorrect: null,
usedNumbers: [],
allowedRedraws: 5,
doneStatus: ''
}
// set the React state to the initial state
state = Game.initialState;
// Reset the game.
resetGame = () => {
this.setState(Game.initialState);
}
}
// ************************************************************
But when I kept watching the video, the tutor implemented it by making a static function that returned the object instead:
// Tutorial implementation ************************************`
class Game extends React.Component {
// store the initial state of the game
static initialState = () => ({
selectedNumbers: [],
numberOfStars: Game.randomNumber(),
answerIsCorrect: null,
usedNumbers: [],
allowedRedraws: 5,
doneStatus: ''
})
// set the React state to the initial state
state = Game.initialState();
// Reset the game.
resetGame = () => {
this.setState(Game.initialState);
}
}
// ************************************************************
So my question is: Is there any difference between these two implementations that might be important? Or are they essentially identical?
I might be over thinking it, but I'm not sure whether there is some aspect to JavaScript or the way Reactjs handles states that might make the tutor's implementation better.
And as an aside, is there a good reason for these to be static? Wouldn't it better if they weren't, so that it would be easier to create different instances with different initial state values if I needed to?