useEffects keeps looping for infinity

58 Views Asked by At

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;
};
2

There are 2 best solutions below

4
Gordon Maloney On BEST ANSWER

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]);
1
AKX On

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.