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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)