What's React Functional Component Equivalent of component​WillUnmount()?

If the useEffect() hook returns a function, React will run it on component unmount (i.e. when it is time to clean up). Providing this cleanup function would serve as the functional component alternative for the class component lifecycle method componentWillUnmount(). It has the following syntax:

useEffect(function callback() {
    // ...

    return function () {
        // perform cleanup...
}, dependencies);

The cleanup function is:

  • Optional; it is used to specify cleanup mechanism for effects;
  • Run after every re-render, and not just once during unmounting.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.