Saif eldeen Adel
Saif eldeen Adel

Reputation: 388

Adding an array in the useEffect dependency array causes an infinte loop

Simple to-do app that lists my tasks and allows me to submit new ones. Connected to a REST API i built and so the tasks are retrieved using a call to that API. Im using useEffect to get all the tasks and store them in a tasks array. This should run every time the array changes (whhen i add a new task, when i delete a task, etc) so i dont have to refresh to see the changes.

useEffect code:

   const [tasks, setTasks] = useState([])
   useEffect(() => { 
        axios.get("http://localhost:8000/api/task-list")
        .then(response => {
            setTasks(response.data)
        })
        .catch(error => {
            console.log(error)
        })
        
    }, [tasks])

Problem now is that theres near infinite calls to my API. It runs indefinitely and not only when the tasks array changes. I think this has something to do with it checking tasks === tasks and them not being the exact same like they seem. But Im not sure.

I'd really appreciate any help cuz I cant just continue like this while making infinite API calls. It only works now cuz the API is mine.

Upvotes: 0

Views: 304

Answers (2)

Margherita Lazzarini
Margherita Lazzarini

Reputation: 173

It's a loop: your effect runs every time tasks changes. The effect itself modifies tasks array, so it runs again, etc.

You should run it just once, when the component mounts, and you can achieve this with an empty array of dependencies:

useEffect(() => { 
        axios.get("http://localhost:8000/api/task-list")
        .then(response => {
            setTasks(response.data)
        })
        ...
        
    }, [])

Then you have to create function callbacks to events that delete/add elements to your list. For example:

const addTask = () => {
  const newTask = ... // the value of your new task, eg. got from an input, ...
  setTasks(prevTasks => prevTasks.push(newTask));
};
...
<Button onClick={addTask}> Add it! </Button>

Upvotes: 0

Adithya
Adithya

Reputation: 1728

if you have tasks in dependency array, then the effect is called whenever tasks changes.

Since you are updating tasks within the effect , it triggers the same effect again. and on and on it goes.

You need to have empty array as dependencies if you want to run it only once, and if its depends on some state, add that.

whats the purpose of having [tasks] as dependency?

Since you can only modify tasks with setTasks it doesn't make sense to have it as dependency. usualy you'll have some other state change (like the press of a button) which should update the tasks.

take a look into the docs for useEffect behavior

Upvotes: 2

Related Questions