Sobes.tech
Middle

Explain the lifecycle of a React component. How to handle unmounting with useEffect?

sobes.tech AI

Answer from AI

The lifecycle of a React functional component with hooks consists of mounting, updating, and unmounting.

The useEffect hook allows you to perform side effects after rendering. To handle component unmounting, you need to return a cleanup function from useEffect. This function will be called before the component unmounts or before the next effect runs.

Example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Code that runs on mounting and updating
    console.log('Component mounted or updated');

    return () => {
      // Cleanup code on unmounting
      console.log('Component will unmount');
    };
  }, []); // Empty dependency array — effect runs once on mount

  return <div>Example component</div>;
}

Thus, the function returned from useEffect serves to handle component unmounting.

Explain the lifecycle of a React component. How to… - sobes.tech