简体   繁体   中英

React useEffect clean up function runs multiple times?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM