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>);
}
const [images, setImages] = useState<Photo[]>(photos)
useEffect(() => {
setImages(photos)
}, [photos])
useEffect
hookfunction 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>);
}
const [images, setImages] = useState<Photo[]>(photos)
useEffect(() => {
setImages(photos)
}, [photos])
Comments
Post a Comment