useEffect(fn, []) is not the new componentDidMount()

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 that useEffect 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:

  1. They’re actually mechanically different, so you might not get what you expect if consider them the same (which we talk about below).
  2. Thinking in terms of time, like “call my side effect once on mount” can hinder your learning of hooks.
  3. Refactoring from classes to hooks will not mean you simply replace your componentDidMount’s with useEffect(fn, []).

Very insightful post!

useEffect(fn, []) is not the new componentDidMount()

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.