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?
The useEffect hook is a function that takes two arguments, the first one being a function which is called effect, as the name suggests and the second one is the array of dependencies. Although the second argument is optional, it is used in many cases depending on the requirement of the application.
Second argument to useEffect React compares the current value of dependency and the value on previous render. If they are not the same, effect is invoked. This argument is optional. If you omit it, effect will be executed after every render.
If you have just made a new project using Create React App or updated to React version 18, you will notice that the useEffect hook is called twice in development mode. This is the case whether you used Create React App or upgraded to React version 18.
You can have multiple useEffects in your code and this is completely fine! As hooks docs say, you should separate concerns. Multiple hooks rule also applies to useState - you can have multiple useState in one component to separate different part of the state, you don't have to build one complicated state object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With