What's the React Functional Component Equivalent of componentDidMount()?

The React useEffect() hook can be used as the functional component alternative for the class component lifecycle method componentDidMount(). It has the following syntax:

useEffect(callback, dependencies);

To make an effect run when the component is mounted, you would have to pass in an empty array for useEffect() dependencies list, for example, like so:

useEffect(() => {
  // ...
}, []);

This would mean that:

  • The effect is run when the component is mounted (after the browser has painted);
  • The effect has no dependencies (such as values from props or state), therefore, it never needs to re-run;
  • Any props and/or state used inside the effect will have their initial values when the effect is run on mount.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.