I'm expecting state to reload on props change, but this does not work and user
variable is not updated on next useState
call, what is wrong?
function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}
The argument passed to useState is the initial state much like setting state in constructor for a class component and isn't used to update the state on re-render
If you want to update state on prop change, make use of useEffect
hook
function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
React.useEffect(() => {
setUser(props.user);
}, [props.user])
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}