Brad Westfall from React Training on why the React hook useEffect(fn, [])
is not the same as componentDidMount()
:
When developers start learning hooks having come from classes, they tend to think “I need to run some code once when we mount, like how
componentDidMount()
works. Ah, I see thatuseEffect
with an empty dependency array does just that. Okay I know how all this works…”This way of thinking gets us into trouble in a few ways:
- They’re actually mechanically different, so you might not get what you expect if consider them the same (which we talk about below).
- Thinking in terms of time, like “call my side effect once on mount” can hinder your learning of hooks.
- Refactoring from classes to hooks will not mean you simply replace your componentDidMount’s with
useEffect(fn, [])
.
Very insightful post!