Lesson 2. Trigger side effects with useEffect 6. Comparison with class components
Although I think it makes more sense to learn how to use useEffect without
comparing it to the class components' lifecycle methods, it’s very tempting to
see the code equivalent to a traditional call to useEffect.
Here is an example of a class component using the three most common lifecycle
methods provided by React: componentDidMount, componentDidUpdate, and
componentWillUnmount.
Result
It displays first a message when the prop name is updating, then another
message two seconds later, assuming nothing changed the name.
Here is the equivalent code written as a function component using useEffect:
Result
At first sight, you will notice that the component is much shorter, but be
careful: one of the reasons is that useEffect handles two behaviors:
- what to do when the component is mounted;
- what to do when the values in the dependencies array (here
name) are updated.
Consequently, converting a class component to a function component using hooks will not always be as easy as it seems. You may have to use some tricks depending on your situation, for instance, if you want to perform an HTTP call when a prop is changed but not at the initial rendering.