useEffect second argument variations in React hook?

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


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.