score:242

Accepted answer

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

score:12

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)


Related Query

More Query from same tag