36

In react hooks, what is the difference between these 3 snippets.

//1.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  });
}

//2.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, []);
}

//3. 

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, [isOn]);
}

Difference between passing empty array, array with an element and not passing at all?

3

2 Answers 2

65

The first will run the effect on mount and whenever the state changes. The clean up will be called on state change and on unmount.

The second will only run the effect once on mount and the clean up will only get called on unmount.

The last will run the effect on mount and whenever the isOn state changes. The clean up will be called when isOn changes and on unmount.

In your examples, the first and last examples will behave the same because the only state that will change is isOn. If the first example had more state, that effect would also refire if the other state were to change.

I guess I should also add is that the order of things would be like: mount: -> run effect, state change: run clean up -> run effect, unmount -> run clean up.

1
  • 3
    Thx a lot, especially for the last two lines!!! Saved my life ;)
    – gignu
    May 21, 2020 at 19:43
11

There are two things that you need to note while using useEffect

Not passing the second argument

In the above case useEffect will clean up the previous effect if the return function was specified and run a new effect on each render of the component

Passing the second argument as empty array

In the above case the effect will be run on initial render and on unmount the effect will be cleared with the return function was specified

Passing the second argument as array of values

In the above case effect will run on initial render and on change of any of the parameters specified within the array. The clean method returned from effect is run before new effect is created

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.