React hook noob here...
Given this example
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
From the doc
React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
Does that mean unsubscribeFromFriendStatus
only gets run when once when component unmounts or every render?
Extending my question:
if unsubscribeFromFriendStatus
gets run every time, and the only way to skip it is by using optional second argument... then doesn't it make it harder to implement the original explicit execution of componentWillMount
and componentWillUnmount
? Say, I want to subscribe
when componentWillMount
, and only run unsubscribe
when componentWillUnMount
?
Does that mean
unsubscribeFromFriendStatus
only gets run when once when component unmounts or every render?
unsubscribeFromFriendStatus
runs every re-render.
Every re-render, even if props.friend.id
never changed, it unsubscribes and resubscribes.
To improve this, run the effect only when props.friend.id
changed.
This is possible by adding it as a dependency to useEffect()
.
useEffect(
() => { /* subscription */ }
, [props.friend.id] // add as dependency
)
doesn't it make it harder to implement the original explicit execution of componentWillMount and componentWillUnmount? Say, I want to subscribe when componentWillMount, and only run unsubscribe when componentWillUnMount?
It doesn't make sense to maintain old subscriptions using old values of props.friend.id
.
A subscription uses a resource (websocket or observer). When unsubscribing during componentWillUnmount
is only unsubscribing the latest value of your props.friend.id
.
What happens to the older subscriptions? Not freed. Thus, you have a memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With