I am studying React through React Offical Document.
I have question about this challenge.
(https://react.dev/learn/updating-objects-in-state#challenges
https://codesandbox.io/s/rztj2r?file=/src/App.js&utm_medium=sandpack)
Assume that the given code is executed as it is without modification,
I understand why {player.score} is disappeared when re-render is occured by handleLastNameChange() event handler called.
But I can’t understand why {player.firstName} isn’t disappeard when re-render is occured by handleLastNameChange() event handler called.
I expected {player.firstName} is disappeared when re-render is occured by handleLastNameChange() event handler called, but it doesn’t work.
2
Answers
If you look in the log, you’ll see this
There are two ways an input can be used: controlled, and uncontrolled. For controlled, you pass in a string to the
value
prop, and react will keep the input in sync with that prop. For uncontrolled, you pass inundefined
for the value prop, and then the input will handle its state itself and ignore the prop.So when the page started, you were passing in a string and thus controlling the input. Then when handleLastNameChange is called, the state accidentally sets firstName to
undefined
, which gets passed into the input. This flips the component to uncontrolled mode, which is not something it is built for. So it fires off the warning and then continues showing what it was previously showing, until something causes it to change.When you handle state updates in React, the component re-renders based on the new state. In the challenge you mentioned, let’s take a closer look at why {player.score} disappears but {player.firstName} doesn’t when handleLastNameChange() is called.