For example if I make a useEffect
hook as useEffect(() => {...},[a,b])
. Will the useEffect
get fired if one of [a,b] changes or when both [a,b] changes ?
Multiple dependencies log(“This useEffect will run either data or siteUrl changes”, data, siteUrl); }, [data, siteUrl]); In the above scenario, useEffect will run when either value of 'data' or 'siteUrl' changes. We can also give more dependencies according to our requirements.
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.
useEffect accepts two arguments. The second argument is optional. Let's use a timer as an example.
You will have no clean-up mechanism that could be executed before running the effect again.
It will fire when either one changes. The way to think of it is that you are telling React:
a
andb
are the things that I am using inside this effect, so if either of them change, my effect will need to cleanup the old version and re-execute with the updated values.
Here's a simple example that allows you to see the behavior:
import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; function App() { const [dependency1, setDependency1] = useState(1); const [dependency2, setDependency2] = useState(1); useEffect( () => { console.log("only dependency1", dependency1, dependency2); }, [dependency1] ); useEffect( () => { console.log("dependency1 and dependency2", dependency1, dependency2); }, [dependency1, dependency2] ); return ( <div className="App"> <button onClick={() => { setDependency1(prev => prev + 1); }} > Change dependency1 </button> <button onClick={() => { setDependency2(prev => prev + 1); }} > Change dependency2 </button> <button onClick={() => { setDependency1(prev => prev + 1); setDependency2(prev => prev + 1); }} > Change both </button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
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