How to use componentWillUnmount with Functional Components in React

Functional components are far more efficient than class based components. Less code is needed to be written to achieve the same goal.

This post explains how functional components can carry out life-cycle events without needing to be turned into a class based component.

Turns out everything can be managed through useEffect.

I have used useEffect in the past to manage API calls, as well as implementing componentWillMount, but never componentWillUnmount. It turns out both are very similar!

 

How to manage componentWillMount with useEffect

To understand how we can use componentWillUnmount with functional components, first we need to look at how the component manages mounting with useEffect.

import React, { useEffect } from 'react';
const ComponentExample => () => {
   useEffect( () => {
      // Anything in here is fired on component mount.
   }, []);
}

 

If we pass an empty array as the second argument, it tells the useEffect function to fire on component render (componentWillMount). This is the only time it will fire.

With this in mind, how can we alter the code to work with componentWillUnmount? Turns out the solution is very simple.

How to manage componentWillUnmount with useEffect

If you add a return function inside the useEffect function, it is triggered when a component unmounts from the DOM. This looks like:

import React, { useEffect } from 'react';
const ComponentExample => () => {
    useEffect(() => {
        return () => {
            // Anything in here is fired on component unmount.
        }
    }, [])
}

 

Combining both solutions

This means that you can use componentDidMount, and componentWillUnmount in the same useEffect function call. Dramatically reducing the amount of code needed to manage both life-cycle events. This means you can easily use componentDidMount and componentWillUnmount within functional components. Like so:

import React, { useEffect } from 'react';
const ComponentExample => () => {
    useEffect(() => {
        // Anything in here is fired on component mount.
        return () => {
            // Anything in here is fired on component unmount.
        }
    }, [])
}