Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I add multiple dependency in React's useEffect second parameter?

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 ?

like image 497
rockfight Avatar asked Mar 08 '19 16:03

rockfight


People also ask

Can a useEffect have multiple dependencies?

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.

What is the second parameter in useEffect?

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.

What is the maximum number of parameters does a react useEffect accepts?

useEffect accepts two arguments. The second argument is optional. Let's use a timer as an example.

What happens if you don't specify the dependencies list in useEffect?

You will have no clean-up mechanism that could be executed before running the effect again.


1 Answers

It will fire when either one changes. The way to think of it is that you are telling React:

a and b 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); 

Edit useEffect dependencies

like image 63
Ryan Cogswell Avatar answered Oct 11 '22 11:10

Ryan Cogswell