Reputation: 9580
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?
Upvotes: 37
Views: 29942
Reputation: 282030
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
Upvotes: 12
Reputation: 2928
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
.
Upvotes: 68