Search code examples
javascriptreactjslistener

How to check if react component detached


have a question, how to check if react component detached from its parent components?

Let’s say I have a react component, that is subscribed to any async events: WebSocket, timer.

I just want to not waste computer resources on listener to this event, when react component no more in use, and deallocate react component as well.

Any though?


Solution

  • React provides various methods to keep track of a component's lifecycle. And in your case you need to track if a component has unmounted. So, there are 2 approach for this based on the type of component you are using:

    Class Component

    Use componentUnmount lifecycle method.

    class YourComponent extends Component {
      constructor(props) {
        super(props);
      }
    
      componentWillUnmount() {
        // this method is invoked immediately before a component
        // is unmounted and destroyed. you can perform any necessary 
        // cleanup in this method, such as invalidating
        // timers, canceling network requests,
        // or cleaning up subscriptions
      }
    
      render() {
        return (
          <div>
            {/* ...contents... */}
          </div>
        );
      }
    }
    

    Functional Component

    Leverage useEffect hook with cleanup.

    const YourComponent = () => {
      useEffect(() => {
        // rest of code
    
        return () => {
          // similar to componentWillUnmount() method, this function
          // would invoke at the time of component's unmount.
        };
      },[]);
    
      return (
        <div>
          {/* ...contents... */}
        </div>
      );
    }