DEV Community

Max Rozen
Max Rozen

Posted on • Originally published at maxrozen.com on

Understanding useEffect: the dependency array

So the question is: How do you stop infinite loops that absolutely hammer your API when you use useEffect?

Let’s take a step back, pause for a moment, and think about what useEffect actually does.

By default, useEffect always runs after render has run. This means if you don’t include a dependency array, and you’re using useEffect to fetch data to display it, you will always trigger another render after useEffect runs.

Unless you provide useEffect a dependency array.

The dependency array in useEffect lets you specify the conditions to trigger it. If you provide useEffect an empty dependency array, it’ll run exactly once, as in this example (CodeSandbox link):

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

export default function DataDisplayer() {
  const [data, setData] = useState('');

  useEffect(() => {
    const getData = async () => {
      const response = await fetch(`https://swapi.dev/api/people/1/`);
      const newData = await response.json();
      setData(newData);
    };

    getData();
  }, []); //<-- This is the dependency array

  if (data) {
    return <div>{data.name}</div>;
  } else {
    return null;
  }
}
Enter fullscreen mode Exit fullscreen mode

What if you wanted to let users decide which id they wanted to query, and forgot to add id to the dependency array? You’d cause an infinite loop.

export default function DataDisplayer(props) {
  const [data, setData] = useState('');

  useEffect(() => {
    const getData = async () => {
      const response = await fetch(`https://swapi.dev/api/people/${props.id}/`);
      const newData = await response.json();
      setData(newData);
    };

    getData();
  }); //<-- Notice the missing dependency array
Enter fullscreen mode Exit fullscreen mode

This is where the dependency array comes in handy.

Adding props.id to it will ensure useEffect only runs if props.id changes:

useEffect(() => {
  const getData = async () => {
    const response = await fetch(`https://swapi.dev/api/people/${props.id}/`);
    const newData = await response.json();
    setData(newData);
  };
  getData();
}, [props.id]); //<-- This is the dependency array, with a variable
Enter fullscreen mode Exit fullscreen mode

(This is an article posted to my blog at maxrozen.com. You can read it online by clicking here.)

Top comments (0)