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!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.
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.
}
}, [])
}
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.
}
}, [])
}
I write regularly about working with React, as well as other developer tips and tricks. If you have a question, send me a message on Twitter @robertmars and I will get back to you as soon as I can! It would be great to hear from you.
Previously published at https://thoughtsandstuff.com/componentwillunmount-functional-components-react