React life cycle methods to useEffect
How to map a React class life cycle methods/hooks to useEffect
Tuesday, November 9, 2021
Common class lifecycle methods
.jsx123456789101112
How can we map those lifecycle hooks to useEffect?
Here are basic templates to convert a class lifecycle method to a useEffect hook:
componentDidMount
Create an empty dependency array and pass it to the useEffect
hook.
.jsx12345
shouldComponentUpdate
Add the dependency array and pass it to the useEffect
hook.
.jsx12345678910
componentWillUnmount
A useEffect
can return a function whose body will be executed when the component is unmounted.
.jsx12345
componentDidUpdate
This is a bit subjective because it's up to the developer to decide how componentDidUpdate
should behave (the simplest is the same as componentDidMount
mapping).
It could also be a combination of componentDidMount
and shouldComponentUpdate
mapping with the addition of a reference variable to check if the component has been mounted as shown below:
.jsx123456789
Additional Note
- You can only define one of each lifecycle method in a
class
component. When using hooks, you can define as manyuseEffect
as you want. - You can only use
useEffect
in afunction
component
Conclusion
The examples above are simple ways to map a class lifecycle hooks
component to a React hooks
, and there are many other ways to do it. The good news is that you don't need to think of mapping lifecycle hooks to useEffect since React hooks introduced a different paradigm on how we can create a React component and how we can manage side-effects. This mapping is only useful when I'm refactoring a class
component to be a function
component. For newer projects, I ought to think that the class component does not exist.