Skip to content
Advertisement

React- Props don’t update when changing their state through the parent

The props on the ‘GameState’ component do not update correctly after changing their state from, they are always one iteration behind what the actual value of the state is as shown in the GIF and the sate is always one iteration behind when I try console.logging it too

enter image description here

JavaScript
JavaScript

expected values:

JavaScript

Code at the GameInfo component:

JavaScript

Advertisement

Answer

Set state is async, so in changeDifficultyHandler, difficulty is still referencing the old value because it hasn’t updated yet. A simple fix would be changing props.onChangeDifficulty(difficulty) to props.onChangeDifficulty(levels[event.target.value]).

That said, storing the same state in two places isn’t best practice. Why not just keep the state in App and pass it to GameInfo as a prop like <GameInfo onChangeDifficulty={changeDifficultyHandler} difficulty={currentDifficulty} />?

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement