React hooks – useEffect hook explained Part 2

2

Effects with cleanup

Some effect required cleanup, like set up subscriptions to some external data source, well in this point we need to do a clean up, because we don’t want to memory leak problems.

If we need to subscribe our component to some service for example, then we can return a cleanup function inside the useEffect, like this:

useEffect(() => { // Effect that return us something (like subscriptions, special requests)
  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }


  // Subcribing to ChatAPI & executing handleStatusChange
  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);

  // Cleanning the side effect
  return () => {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };
});

Also you can read my first post:

React hooks – useEffect hook explained Part 1

By Criss