In useEffect, what's the difference between providing no dependency array and an empty one?

ReactjsReact HooksUse Effect

Reactjs Problem Overview


I gather that the useEffect Hook is run after every render, if provided with an empty dependency array:

useEffect(() => {
  performSideEffect();
}, []);

But what's the difference between that, and the following?

useEffect(() => {
  performSideEffect();
});

Notice the lack of [] at the end. The linter plugin doesn't throw a warning.

Reactjs Solutions


Solution 1 - Reactjs

It's not quite the same.

  • Giving it an empty array acts like componentDidMount as in, it only runs once.

  • Giving it no second argument acts as both componentDidMount and componentDidUpdate, as in it runs first on mount and then on every re-render.

  • Giving it an array as second argument with any value inside, eg , [variable1] will only execute the code inside your useEffect hook ONCE on mount, as well as whenever that particular variable (variable1) changes.

You can read more about the second argument as well as more on how hooks actually work on the official docs at https://reactjs.org/docs/hooks-effect.html

Solution 2 - Reactjs

Just an addition to @bamtheboozle's answer.

If you return a clean up function from your useEffect

useEffect(() => {
  performSideEffect();
  return cleanUpFunction;
}, []);

It will run before every useEffect code run, to clean up for the previous useEffect run. (Except the very first useEffect run)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul Razvan BergView Question on Stackoverflow
Solution 1 - ReactjsbamtheboozleView Answer on Stackoverflow
Solution 2 - ReactjsAnkur MarwahaView Answer on Stackoverflow