react useeffect

In react life-cycle there are sets of method that being called when a component is being created and inserted to the DOM. Example when creating a component for the first time.

ComponentDidMount is called later when the componen is added to the DOM. Usually this function is used to run additional code after react has updated the DOM. (Eg, fetching external data, manual updating DOM mutation). This function has "side-effect"

When using a Function Component, react has similar method called useEffect

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {    
    // Update the document title using the browser API    
    document.title = `You clicked ${count} times`;  
  });
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

This example shows function without cleanup method.

To create a effect that willbe cleanup after Unmount & every render,

function FriendStatus(props) {
    const [isOnline, setIsOnline] = useState(null);

    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);
        };
    });
    
    if (isOnline === null) {
        return 'Loading...';
    }
    return isOnline ? 'Online' : 'Offline';
}

Only run when some data change

Running useEffect function for every render might not be good for performance. A second argument to the useEffect can be pass to only run the function when the listed data changed

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Last updated