Sobes.tech
Middle

In class components, there is a method componentWillUnmount. How to implement an equivalent in a functional component?

sobes.tech AI

Answer from AI

In React functional components, the equivalent of the componentWillUnmount method from class components is the cleanup function returned from the useEffect hook.

Example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // code that runs on mounting

    return () => {
      // cleanup code that runs on unmounting
      console.log('Component unmounted');
    };
  }, []); // empty dependency array ensures this runs only on mount and unmount

  return <div>Example</div>;
}

Thus, if you pass an empty dependency array to useEffect, the function inside return will be called upon component unmounting, which corresponds to the behavior of componentWillUnmount.