function UserCard({ user }) {
let defaultUserName = user.nicknames[0];
let [selectedNickname, setSelectedNickname] = React.useState(defaultUserName);
// The selected nickname becomes invalid when the user is changed!!!
const selectedNicknameIsValid = user.nicknames.includes(selectedNickname);
return (<div>
<UserCardWithNickName user={user} selectedNickname={selectedNickname} />
<SelectNickName user={user} setSelectedNickname={setSelectedNickname} />
</div>);
In the above snippet the component's state holds the selected nickname from the list of user nicknames. But when the user changes in the parent component this component is re-rendered with the same state. So the nickname in the state is for the wrong user.
What is the preferred way to handle this? A lot of google searching couldn't find much discussion.
Am I doing this in some fundamental non-react way?
Is the preferred solution to use useEffect to fix the state when it becomes invalid as discussed here React.useState does not reload state from props?
Working example on codesandbox