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

32,858

Solution 1

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

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)

Share:
32,858
Paul Razvan Berg
Author by

Paul Razvan Berg

Founder at Sablier. On Twitter as PaulRBerg. Donations welcome at paulrberg.eth.

Updated on April 22, 2021

Comments

  • Paul Razvan Berg
    Paul Razvan Berg about 3 years

    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.

  • Patrick
    Patrick over 3 years
    Is there a use-case for ever putting null? Isn't it just the same as not putting the code in a useEffect hook?
  • Rakha Kanz Kautsar
    Rakha Kanz Kautsar over 3 years
    @Patrick useEffect will be run after render while just putting the code there will be run before render
  • jaquinocode
    jaquinocode almost 3 years
    You forgot to mention that the cleanup function will also always run on unmount. So, for example, if the dependency array is empty ([]), then the cleanup function will only run once: on unmount. See "Notes" section here (scroll down).
  • R.Nosratabad
    R.Nosratabad over 2 years
    according to a note in: reactjs.org/docs/…, passing empty array will cause run it also on componentWillUnmount in addition to componentDidMount
  • JuJu
    JuJu over 2 years
    When I give the dependency array a variable (Ex: [myList]) to display my list items after I insert them with axios.post and I see that it keeps sending requests every second in my Network tab. Will this affect the performance of my app?
  • bamtheboozle
    bamtheboozle over 2 years
    well, yes. you're basically running an infinite loop