One of the more confusing aspects of the useEffect() hook is the dependency array.

As a reminder, here’s the syntax for useEffect:

useEffect(() => {}, [])

The dependency array is the second parameter, []. Whenever any of the dependencies specified in the array change, the function is re-executed.

But what does that really mean?

To understand, let's take a step back and look at Effects in React in general.

Effects

Suppose you are building a dashboard with a list of patients, and you want your List component to fetch data from an API every time the component renders (in our case, probably on something like page load or a refresh button click). In React, you would do this using an Effect. Unlike events, effects are triggered by rendering itself rather than a particular interaction like a click. Effects run at the end of the rendering process after the screen updates and are meant to help you synchronize your component to some external system.

Writing an Effect

To declare an effect in your component, you use the useEffect React hook, and call it at the top level of your component.

import React, {useState} from "react";

const PatientList = ({url}) => {
  const [patients, setPatients] = useState("");

    useEffect(() => {
	async function fetchData() {
      // Call fetch as usual
      const res = await fetch(
       Url + "/patients"
      );

      // Pull out the data as usual
      const json = await res.json();

      // Save the posts into state
      // (look at the Network tab to see why the path is like this)
      setPatients(json.data.children.map(c => c.data));
    }

        fetchData();
    })

  return (
    <ul>
      {patients.map(patient => (
        <li key={patient.id}>{patient.name}</li>
      ))}
    </ul>
  );
};

Every time your component renders, React will update the screen and then run the code inside useEffect.

But what if you don’t want the code inside useEffect to run after every render?

For example, in the code above, the component re-renders after every state change, which means that every time `patients` changes, the code inside `useEffect` reruns. Since `patients` is changed in useEffect, this creates an infinite re-render.

You can tell React to skip unnecessarily rerunning the effect by specifying an array of dependencies as the second argument to the useEffect call. Only if one of the dependencies has changed since the last render, will the effect be rerun. If you specify an empty array, then the effect will only be run once, upon component mount.

import React, {useState} from "react";

const PatientList = ({url}) => {
  const [patients, setPatients] = useState("");

    useEffect(() => {
	async function fetchData() {
      // Call fetch as usual
      const res = await fetch(
       url + "/patients"
      );

      // Pull out the data as usual
      const json = await res.json();

      // Save the posts into state
      // (look at the Network tab to see why the path is like this)
      setPatients(json.data.children.map(c => c.data));
    }

        fetchData();

    }, [url])

  return (
    <ul>
      {patients.map(patient => (
        <li key={patient.id}>{patient.name}</li>
      ))}
    </ul>
  );
};

In the code above, the code inside useEffect will only be rerun if the url prop changes.

Callout: The behaviors without the dependency array and with an empty [] dependency array are very different:

useEffect(() => {
 // This runs after every render
});

useEffect(() => {
 // This runs only on mount (when the component appears)
}, []);

ESLint rules

You might be wondering how to go about figuring out which dependencies to include in the dependency array. Fortunately, the React team has put out a plugin, ESLint rules for React Hooks, that will automatically parse your code and let you know what to include.

With this plugin installed, if you specify an empty dependency array, but the code inside useEffect actually has a dependency, then you’ll see a lint error.

Now, let’s go through some case studies of how to use the dependency array in useEffect in real world ways.

Case study # 1: what’s causing my infinite rerenders?

Developers who are just starting out with useEffect often find themselves writing effects that result in infinite renders. If you find yourself in this situation, it’s good to go through the checklist below to make sure that you’ve covered all your bases.

  1. Make sure that you are not missing a dependency array. As noted previously in this blog post, there’s a big difference in behavior between an empty dependency array and no dependency array.

useEffect(() => {
 // This runs after every render causing infinite renders
});

useEffect(() => {
 // This runs only on mount (when the component appears)
}, []);

2. If you do have a dependency array, make sure that inside the useEffect, you’re not setting state variables that are also dependencies. If you are, the effect will run every time those state variables are changed, creating an infinite loop. For example:

const [serviceList, setServiceList] = useState([]);
var [bookButton, setBookButton] = useState(false);
useEffect(()=>{
      fetch('/viewall')
       .then((response) => {
           setServiceList(response.data);
           serviceList.filter(function(serv){
                   if(serv.userId === userId){
                       setBookButton(false);
                   }
                   else{
                       setBookButton(true);
                  }
              }
           );

           console.log(serviceList1);
       })
   }, [serviceList, bookButton]);

In this example, `serviceList`, and `bookButton` are state variables that are getting reset inside the effect. Every time they change, they trigger another rerun of the effect, ad nauseam. To get rid of the infinite loop, you need to remove the serviceList and bookButton from the dependency list.


const [serviceList, setServiceList] = useState([]);
var [bookButton, setBookButton] = useState(false);

useEffect(()=>{
      fetch('/viewall')
       .then((response) => {
           setServiceList(response.data);
           serviceList.filter(function(serv){
                   if(serv.userId === userId){
                       setBookButton(false);
                   }
                   else{
                       setBookButton(true);
                  }
              }
           );
           console.log(serviceList1);
       })
   }, []);

Case study #2: Passing objects, arrays, and functions in the dependency array

In the examples above, we have primarily passed primitive types – numbers, strings, and booleans – into the dependency array. What about objects, arrays, and functions? These complex values pose a challenge because React uses referential equality to check whether these complex values have changed.

In particular, React checks to see if the object in the current render points to the same object in the previous render. The objects have to be the exact same object in order for useEffect to skip running the effect. So even if the contents are the exact same, if a new object is created for the subsequent render, useEffect will rerun the effect.

Objects and arrays in the dependency array

If you have an object or array as a dependency of useEffect, and then update that object inside the effect, you effectively create a new object with a new reference and cause an infinite loop.

// this will have an infinite loop
useEffect(() => {
   if (patient.name === 'jimmy') {
     setPatient(p => ({...p, age: p.age + 1}));
   }
 }, [patient]);

The way to address this is to avoid using the entire object as a dependency: instead, you should use a specific property only.

Functions

What about if you want to pass a function to a dependency array? Consider the code below. It’s defining an async function `initializeAccount` that is calling out to several API’s and setting some state.

const [user, setUser] = useState(null)
const [profile, setProfile] = useState(null)
const [posts, setPosts] = useState(null)

const initializeAccount = async () => {
 try {
   const user = await fetch('api/user/')
   const profile = await fetch('api/profile/')
   const posts = await fetch('api/posts/')
   if (user) {
     setUser(user.data)
   }
   if (profile) {
     setProfile(profile.data)
   }
   if (posts) {
     setPosts(posts.data)
   }
 } catch (e) {
   console.log('could not initialize account')
 }
}

useEffect(() => {
 initializeAccount()
 return () => console.log('unmount')
}, [])

If you run this example as written, ESLint will complain that `initializeAccount` should actually be in the dependency array.

While you can technically overwrite the linter, the linter tends to flag antipatterns that you want to avoid. It may also be the case that you’re passing the function as a prop to your component. That function can be one of several different functions. You want to make sure that if you receive a new function, you call out the effect once more.

But when you actually add `initializeAccount` to the dependency array, that creates another infinite loop

useEffect(() => {
 initializeAccount()
 return () => console.log('unmount')
}, [initializeAccount])

Why is this?

The issue is that similar to the object example above, upon each render cycle, `initializeAccount` is redefined and has a different reference.

The solution here is to use the useCallback hook to memoize the function so that on subsequent updates of the component, the function keeps its referential equality, and therefore does not trigger the effect.

const initializeAccount = useCallback(async () => {
 try {
   const user = await fetch(url + 'api/user/')
   const profile = await fetch(url + 'api/profile/')
   const posts = await fetch(url + 'api/posts/')
   if (user) {
     setUser(user.data)
   }
   if (profile) {
     setProfile(profile.data)
   }
   if (posts) {
     setPosts(posts.data)
   }
 } catch (e) {
   console.log('could not initialize account')
 }
}, [])

useEffect(() => {
 initializeAccount()
 return () => console.log('unmount')
}, [initializeAccount])

useCallback also takes its own dependency array, which you can use to pass any variables that the function depends on. For example, let’s say that the component actually takes in a url prop, which is used in the API request. In the code below, because you have added the url s a dependency in the useCallback’s dependency array, the initializeAccount function will be re-initialized every time that url changes. This, in turn, will trigger a re-rerun of the useEffect.

const initializeAccount = useCallback(async () => {
 try {
   const user = await fetch(url + 'api/user/')
   const profile = await fetch(url + 'api/profile/')
   const posts = await fetch(url + 'api/posts/')
   if (user) {
     setUser(user.data)
   }
   if (profile) {
     setProfile(profile.data)
   }
   if (posts) {
     setPosts(posts.data)
   }
 } catch (e) {
   console.log('could not initialize account')
 }
}, [url])

useEffect(() => {
 initializeAccount()
 return () => console.log('unmount')
}, [initializeAccount])

Case study # 3: Running on state change – autosuggest

A common feature in many products is autosuggest in a textbox. The user starts typing in a textbox and a dropdown menu suggests a bunch of phrases. You can use useEffect to build this feature.

In the code below, the useEffect filters for suggestions that contain what has been typed in the input box. `inputValue` is a dependency in the useEffect dependency array, which means that every time `inputValue` is updated (every time that a new character is typed into the input box), then the effect will rerun.

import React, { useEffect, useState } from "react";

const array = [
  'change', 'challenge', 'charles'
];

const AutoCompleteInput = () => {
   const [inputValue, setInputValue] = useState('');
   const [filteredArray, setFilteredArray] = useState(array);

   const inputValueHandler = e => {
       setInputValue(e.target.value);
   };

   useEffect(() => {
       setFilteredArray((_) => {
           const newArray = array.filter(item => item.includes(inputValue));
           return newArray;
       });
   }, [inputValue]);

   return (
           <div>         
               <input type="text" id="input-value" onChange={inputValueHandler} />
           </div>
   )

};

export default AutoCompleteInput;

Case study # 4 - Your effect uses a particular value, but you don’t want to rerun the effect when that value changes

Let’s say that you have an effect that uses a particular value. ESLint says that you have to include this value in the dependency array, but you don’t actually want to rerun the effect when that value changes. For example, let’s consider the code below where we want different functions to run depending on the size of the screen.

const patientList = ({
 isDesktop,
 selectedPatient
}) => {

 useEffect(() => {
   isDesktop ? showPatientModal() : showPatientPage()
 }, [selectedPatient])

 return (
   <div className="App">
     <h1>{selectedPatient.name}</h1>
     <p>{selectedPatient.birthday}</p>
   </div>
 );
}

Let’s say in this example that you don’t actually want to rerun the effect when the browser window changes size. You only want to rerun the effect when the `selectedPatient` changes. But the linter complains that `isDesktop` is not in the dependency array.

The correct solution here is to use `isDesktop` and `selectedPatient` to initialize component state variables. Whenever `selectedPatient` changes, the first useEffect will update both states with the passed-in props, and trigger the second useEffect() to rerun on the next render. By refactoring the code this way, you are able to remove isDesktop from the main effect itself, and not have to include it in the dependency array while keeping the linter happy.

const patientList = ({
 isDesktop,
 selectedPatient
}) => {
 const [desktop, setDesktop] = useState(isDesktop)
 const [patient, setPatient] = useState(selectedPatient)

 useEffect(() => {
   if (patient !== selectedPatient) {
     setDesktop(isDesktop)
     setPatient(selectedPatient)
   }
 }, [isDesktop, selectedPatient, patient])

 useEffect(() => {
   if (desktop) showPatientModal()
   Else showPatientPage()
 }, [desktop, patient])

 return (
   <div className="App">
     <h1>{selectedPatient.name}</h1>
     <p>{selectedPatient.birthday}</p>
   </div>
 )
}

Conclusion

The dependency array in useEffect can be confusing and as a result its nuances are often disregarded. From the examples above, though, you can see that it plays a major role in regulating the state management of React components and writing clean, “pure” React code.