useEffect

useEffect is a hook that is used to perform some side-effects in a component like a network calls, or subscribing to an event.

  • useEffect is a combination of componentWillUpdate, componentWillUnmount and componentDidMount. It is of two types: one without a cleanup function and another with a cleanup function.
    • Cleanup functions are recommended in useEffect so that we can stop memory leaks. Clean-up functions are run before applying new effects to the component. They are similar to componentWillUnmount.
  • There can be multiple useEffect in a single component where each useEffect can focus on different things. useEffect comes with a dependency array which means the useEffect will only run if the variable in the dependency array changes.
  • Usage of useEffect:
useEffect(() => {
  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  return () => {// this is a cleanup function
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };

}, [props.friend.id]);// 👆this is a dependency array rerun the useEffect if props.friend.id changes .