dnp_akil
dnp_akil

Reputation: 105

Infinite Loop while using react hook

I'm learning react for past few days and while using useEffect hook i'm getting infite loop over setting my state variable.

Can anyone tell me what's going on and how to overcome this enter image description here

Here's my code

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

const TodoEntry = () => {

  const [todos, setTodos] = useState('');

  useEffect(() => {
    axios.get('http://localhost:5000/api/todos')
     .then(res => { setTodos(res.data); console.log(todos) })
     .catch(err => console.log(err))
  },[todos]);

  return (
    <div>
      <h1>Todo App</h1>
   </div>
  );
};

export default TodoEntry;

Upvotes: 1

Views: 139

Answers (2)

Yousaf
Yousaf

Reputation: 29344

Couple of problems in your code:

  • Since getTodos function is a dependency of useEffect hook, every time state updates, new getTodos function is created which then triggers the useEffect hook.

  • You don't need to chain then function when using async-await syntax. You can just await the result of axios.get(...).

To fix the first problem of infinite loop, use one of the following options:

  • Wrap the getTodos function in useCallback hook. For details, see useCallback.

    Since, getTodos function calls displayTodos, you will need to wrap it in useCallback hook and add displayTodos in the dependency array of useCallback hook that wraps getTodos function. In my opinion, it is better to just remove the displayTodos function and update the state inside getTodos function

    const getTodos = useCallback(async () => {
       try {
          const res = await axios.get('http://localhost:5000/api/todos')
          setTodos(res.data);
       } catch(err) {
          console.log(err);
       }
    }, [setTodos]);
    

    Demo

    Edit cold-darkness-xgjwp

  • Put the code inside getTodos inside useEffect hook and remove the getTodos function.

    useEffect(() => {
      axios.get("http://localhost:5000/api/todos")
       .then(res => setTodos(res.data))
       .catch(err => console.log(err));
    
    }, [setTodos]);
    

    Demo

    Edit blissful-darkness-1q7ng

Upvotes: 2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

This is because the dependency list for your useEffect call is a function. You probably meant to add the todos data itself.

  useEffect(() => {
    getTodos();
  },[todos]);

Upvotes: 0

Related Questions