DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Dependency list in the useEffect hook

The dependency list in the useEffect hook is an optional second argument that determines when the effect function should run. It is an array of dependencies, and the effect function will run if any of the dependencies in the list have changed since the last render. If the dependency list is empty ([]), the effect will run only once after the initial render, simulating the behavior of componentDidMount.

Now, let's explain the differences between the three code examples and their behavior and working process:

  1. Code Example 1:
import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("useEffect call", count);
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  }, [count]);

  return (
    <div className="App">
      <h1>I have rendered {count} times!</h1>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Code Example 1 uses [count] as the dependency array. This means the effect function inside the useEffect hook will run whenever the count state changes. The useEffect is set to run after each render, and since it modifies the count state using setCount, it causes the component to re-render. As a result, the effect will run repeatedly, creating an infinite loop that increments the count state every second.

  1. Code Example 2:
import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("useEffect call", count);
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  }, []);

  return (
    <div className="App">
      <h1>I have rendered {count} times!</h1>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Code Example 2 uses an empty dependency array []. This means the effect function inside the useEffect hook will run only once after the initial render, simulating the behavior of componentDidMount. The useEffect runs only once, setting up the setTimeout to increment the count state after one second. Since there are no dependencies in the array, the effect doesn't depend on any state or props changes, and it will not run again after the initial render.

  1. Code Example 3:
import "./styles.css";
import { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("useEffect call", count);
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  });

  return (
    <div className="App">
      <h1>I have rendered {count} times!</h1>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Code Example 3 doesn't have a dependency array, which means the effect function inside the useEffect hook will run after each render. Since there is no dependency list, the effect is dependent on all state and props in the component. The useEffect runs after the initial render and sets up the setTimeout to increment the count state after one second. However, because the effect runs after each render, it creates an infinite loop that increments the count state every second.

In summary:

  • Code Example 1 creates an infinite loop due to the dependency on count, resulting in repeated renders and updates to the count state.
  • Code Example 2 increments the count state only once after the initial render since there are no dependencies in the dependency array.
  • Code Example 3 also creates an infinite loop because there is no dependency array, causing the component to re-render repeatedly and continuously incrementing the count state.

Top comments (2)

Collapse
 
brense profile image
Rense Bakker

I understand you're trying to give an example of how the dependency array works, but never ever ever update the state value of a dependency inside useEffect. Its the fastest way to rapidly kill the performance of your React app. It would be better to make a separate side effect that only runs on mount, with an interval to update the state:

useEffect(() => {
  const interval = setInterval(() => {
    setCount(count => count += 1)
  }, 1000)
  // Very important, ALWAYS provide a cleanup for intervals and timeouts:
  return () => clearInterval(interval)
}, [])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
abubakardev profile image
Imam Abubakar

You've provided an essential piece of advice for optimizing React app performance when using the useEffect hook with dependencies. Updating the state value of a dependency inside useEffect can indeed lead to unnecessary re-renders, impacting performance negatively. Your suggested approach of using a separate side effect with an interval and providing a cleanup function is a more efficient way to handle such scenarios. By doing this, you ensure the interval is properly cleared when the component unmounts, preventing memory leaks. Thanks for sharing this valuable insight!

Just wanted to break it down a little further