React: useEffect explained with lifecycle methods

React’s useEffect hooks combines componentDidMountcomponentDidUpdate and componentWillUnmount lifecycle methods. This is very useful for the following reasons: it reduces the amount of code, simplifies the code and allows for multiple useEffect hooks to be called in a single component.

You can read more about the useEffect hook here: React docs

Sometimes, we’d like only a single of those lifecycle methods to run. The following cheat-sheet will help you achieve the “effect” you’re looking form.

componentDidMount eqivalent

In order to have this hook run only once (when a component is mounted), we need to set an empty array as a hook dependency.

useEffect(() => {
  /* ComponentDidMount code */
}, []);

componentDidUpdate eqivavlent

In order to have this hook run when the component is updated (this includes mounting), we need to set at least one variable as hook’s dependency (in this case, var1 and var2).

useEffect(() => {
  /* componentDidUpdate code */
}, [var1, var2]);

componentWillUnmount eqivavlent

In order to have this hook run when the component is unmounted, we need to return a function from the hook. Dependency array doesn’t affect this functionality.

useEffect(() => {
  return () => {
   /* componentWillUnmount code */
  }
}, [var1, var2]);

All three combined

useEffect(() => {

  /* componentWillMount code + componentDidUpdate code */

  return () => {
   /* componentWillUnmount code */
  }
}, [var1, var2]);

Thank you for taking the time to read this post. If you’ve found this useful, please share and feel free to comment.