Cnerd Mahadi
Cnerd Mahadi

Reputation: 11

useEffects keeps looping for infinity

Pardon me if this is a silly question. Im a new react learner. Im trying using a create react app. I am using a custom hook for API handling only. Now I want the useEffect to run only when the data changes. Thats why I put it in dependency. But yet it keeps rendering for infinity. What is the problem? Or how should I handle this? Thank you.

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

export const useAPI = (url, options) => {
    const [data, setData] = useState([]);

    const getDogCollection = useCallback(() => {
        fetch(url, options)
            .then((res) => res.json())
            .then((result) => {
                console.log(data, "----DI---", result);
                setData(result);
            });
    }, []);

    useEffect(() => {
        getDogCollection();
    }, [data]);

    return data;
};

Upvotes: -1

Views: 58

Answers (2)

Gordon Maloney
Gordon Maloney

Reputation: 392

It's because you've given data as one of the dependencies, but the function called in your useEffect updates data, so it then runs again.

You can change it to the length, like this, and it should work:

useEffect(() => {
    getDogCollection();
}, [data.length]);

Upvotes: 0

AKX
AKX

Reputation: 168863

You'll just want url and options to be the dependencies, not data (because you set it in the effect!).

import { useEffect, useState } from "react";

export const useAPI = (url, options) => {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch(url, options)
      .then((res) => res.json())
      .then(setData);
    // TODO: add error handling...
  }, [url, options]);
  return data;
};

However, you'll probably just want to look at swr instead of writing this hook yourself.

Upvotes: 1

Related Questions