There is a nice workaround to implement componentDidMount
and componentWillUnmount
with useEffect
.
Based on the documentation, useEffect
can return a "cleanup" function. this function will not be invoked on the first useEffect
call, only on subsequent calls.
Therefore, if we use the useEffect
hook with no dependencies at all, the hook will be called only when the component is mounted and the "cleanup" function is called when the component is unmounted.
useEffect(() => {
console.log('componentDidMount');
return () => {
console.log('componentWillUnmount');
};
}, []);
The cleanup return function call is invoked only when the component is unmounted.
Hope this helps.