'Why useEffect in Redux state is causing infinite loop:

I'm having this issue when I fetch a list of items from api. The axios make a get request in the action. send to reducer and makes change in the state. So I want the list to update only when the user adds, removes or update a item. I'm using the useEffect hook passing the list as dependency to change, but it's just fetching in infinite loop, affecting the performance tremendously.

Action creator:

import axios from "axios";
const BASE_URL = "https://localhost:5001/api";

export function getList() {
  return (dispacth) => {
    return axios.get(`${BASE_URL}/billingCycles`).then((res) =>
      dispacth({
        type: "BILLING_CYCLES_FETCHED",
        payload: res.data,
      })
    );
  };
}

Reducer:

const INITIAL_STATE = { list: [], billingCycle: {}, credits: [], debts: [] };

// eslint-disable-next-line import/no-anonymous-default-export
export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case "BILLING_CYCLES_FETCHED":
      return { ...state, list: action.payload };
  ..MORE CASES BELOW...
  }
}

List component:

import React, { useEffect } from "react";

import ListItem from "./ListItem";

import { getList } from "../../store/actions/billingCycleActions";
import { setCreate } from "../../store/actions/modalActions";
import { useDispatch, useSelector } from "react-redux";

function List() {
  const dispatch = useDispatch();
  const billingCycles = useSelector((state) => state.billingCycles.list);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => dispatch(getList()), [billingCycles]);

  return (
    <div>
      <div className="mb-3 d-flex justify-content-lg-start">
        <button
          className="btn btn-success"
          onClick={() => dispatch(setCreate(true))}
        >
          <i className="fas fa-plus m-1"></i>
          Novo ciclo!
        </button>
      </div>
      <table className="table table-hover border ">
        <thead className="border">
          <tr>
            <th>Nome</th>
            <th>Mês</th>
            <th>Ano</th>
            <th>Ações</th>
          </tr>
        </thead>
        <tbody>
          {billingCycles &&
            billingCycles
              .map((el) => {
                return (
                  <ListItem
                    index={el.id}
                    name={el.name}
                    month={el.month}
                    year={el.year}
                  />
                );
              })
              .reverse()}
        </tbody>
      </table>
    </div>
  );
}

export default List;

Here's a image of the Redux debug tool: enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source