Reputation: 87
const UserProfile = ({
user=[],
}) =>{
useEffect(() => {
console.log("mounted")
console.log("inside: "+user.id)
},[]);
console.log("outside :"+user.id)
return(
<Text>hello</Text>
);
};
Why is This returning this logs? I think user.id in useEffect should return the same
Upvotes: 0
Views: 44
Reputation: 341
Your effect is called only once, while mounted. At the point of mounting there's no user
value set, as you can see in logs (outside :undefined
and inside: undefined
). Then, when you pass user
with id
to UserProfile
component, effect is not called, because registering effect with empty dependency array indicates, that it will be called only on mount.
Please check: https://reactjs.org/docs/hooks-effect.html (last yellow note section)
If you want your effect to be called everytime user
property changes, add it to dependency array like below:
useEffect(() => {
...
},[user])
Upvotes: 2
Reputation: 358
Try this:
useEffect(() => {
if (!user.id) {
return
}
console.log("mounted")
console.log("inside: "+user.id)
},[user])
Upvotes: 0