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.
}
}, [])
}
#reactjs #react #react-hook #function