rockfight
rockfight

Reputation: 1996

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 ?

Upvotes: 63

Views: 67907

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81016

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

Upvotes: 94

Related Questions