DEV Community

gaurbprajapati
gaurbprajapati

Posted on

Understand the concept of dependency list in useEffect in reactjs

When using the useEffect hook in React, the plays a crucial role in determining when the effect should be run. Let's explore the differences between adding and not adding a dependency list in more detail:

  1. Adding a Dependency List:
   import React, { useEffect, useState } from 'react';

   function MyComponent({ prop1, prop2 }) {
     useEffect(() => {
       // Effect code here
     }, [prop1, prop2]);

     // Rest of the component code
   }
Enter fullscreen mode Exit fullscreen mode
  • When you provide a dependency list ([prop1, prop2]), the effect will only be triggered if any of the dependencies change between renders. The effect will run initially after the initial render and then again whenever the listed dependencies change.
  • If any of the dependencies have changed, the previous effect cleanup function will run before the new effect is triggered.
  • This approach allows you to control when the effect should be re-executed based on specific prop or state changes, preventing unnecessary re-runs of the effect when those dependencies remain unchanged.
  1. Not Adding a Dependency List:
   import React, { useEffect } from 'react';

   function MyComponent() {
     useEffect(() => {
       // Effect code here
     });

     // Rest of the component code
   }
Enter fullscreen mode Exit fullscreen mode
  • When you don't provide a dependency list (or provide an empty list []), the effect will run after every render of the component, including the initial render.
  • This means that the effect code will be executed on every component render, regardless of whether any specific prop or state has changed.
  • It can lead to performance issues and unnecessary re-execution of code if the effect is not actually dependent on any specific prop or state change.

In summary, by providing a dependency list, you control when the effect should be re-executed based on specific prop or state changes. This helps optimize performance by preventing unnecessary re-runs of the effect. On the other hand, not providing a dependency list will cause the effect to run after every render, potentially leading to performance issues if the effect doesn't actually depend on any specific changes.

Top comments (0)