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

5

217

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.

Teammate answered 27/10, 2019 at 12:28 Comment(0)
A
403

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

Alerion answered 27/10, 2019 at 12:33 Comment(7)
Is there a use-case for ever putting null? Isn't it just the same as not putting the code in a useEffect hook?Draughts
@Draughts useEffect will be run after render while just putting the code there will be run before renderChlorosis
according to a note in: reactjs.org/docs/…, passing empty array will cause run it also on componentWillUnmount in addition to componentDidMountMaudmaude
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?Fontana
well, yes. you're basically running an infinite loopAlerion
@Draughts Putting dependency as null is same as having empty array. It will on render content inside useEffect once.Forb
Is there an official name for the empty array pattern? So far I only see this circumscribed and it's hard to google for questions I have that are related to this pattern.Detach
B
26

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)

Blueprint answered 22/4, 2021 at 7:13 Comment(1)
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).Bone
S
6

Late to the party but thought of putting this example here which I did for my own understanding after reading above comments:

import './App.css';
import { useEffect, useState } from 'react';

function App() {

  const [name, setName] = useState('John');
   useEffect(()=>{
    console.log("1- No dependency array at all");
  });
  useEffect(()=>{
    console.log("2- Empty dependency array");
  }, []);
  useEffect(()=>{
    console.log("3- Dependency array with state");
  }, [name]);

  const clickHandler = () => {
    setName('Jane');
  }
  return (
    <div className="App">
      <button onClick={clickHandler}>Click to update state</button>
      <p>{`Name: ${name}`}</p>
    </div>
  );
}

export default App;

OUTPUT

On page load

 1- No dependency array at all
 2- Empty dependency array
 3- Dependency array with state
 1- No dependency array at all
 2- Empty dependency array
 3- Dependency array with state

On button click -state update

 1- No dependency array at all
 3- Dependency array with state
Supercargo answered 24/1, 2023 at 10:5 Comment(1)
Everywhere I see says that an empty array will run only once. I'm trying to use this to bind an event handler. but with empty array it don't run at all.Alphabetic
C
3

The latest docs have a good rundown on the differences:

https://react.dev/reference/react/useEffect#examples-dependencies

Passing an array

If you specify the dependencies, your Effect runs after the initial render and after re-renders with changed dependencies.

useEffect(() => {}, [a, b]);

Passing an empty array

If your Effect truly doesn’t use any reactive values, it will only run after the initial render (though twice in development). This now causes a linter warning.

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

Passing no array

If you pass no dependency array at all, your Effect runs after every single render (and re-render) of your component.

useEffect(() => {});
Cooky answered 3/10, 2023 at 9:34 Comment(0)
P
1

The difference is that if you don't provide the empty array dependency, the useEffect() hook will be executed on both mount and update.

Piste answered 16/6, 2022 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.