简体   繁体   中英

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在此处输入图像描述

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;

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

    编辑冷黑暗-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

    编辑 blissful-darkness-1q7ng

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM