Be careful with mapStateToProps, you should only select the part of the store you're interested in, otherwise performance problems could occur

const mapStateToProps = state => ({auth: state.auth});

A little explanation how react-redux connect works,

  1. each time there is a modification in the store (from the reducers), the mapStateToProps functions of all the connected components are executed
  2. if the one prop in the returned object is different from the previous one (the operator === is used) then the component is re-rendered otherwise it does nothing.

In your example, as you select all the props of the store, your component will be re-rendered for each modification in the store

Answer from Olivier Boissé on Stack Overflow
🌐
GitHub
github.com › reduxjs › redux-thunk › issues › 184
Multiple dispatches cause infinite loop · Issue #184 · reduxjs/redux-thunk
March 20, 2018 - export const getAllHomeTours = ... this causes the infinite loop } ); } catch (e) { dispatch(loading(false)); } }; If i dispatch the loading(false) action the app runs into an infitie loop where this action gets called because the component i'm working on keeps remounting due to the HOC that handles loading. const withLoading = Component => { class WithLoading extends React.Component ...
Author   borisyordanov
Discussions

React dispatch going in the infinite loop - javascript
While making a post request my request is going in a loop. Not sure why it's happening. Its happening at the handleSubmit of the form. I referred few question from stackoverflow but it did not help... More on stackoverflow.com
🌐 stackoverflow.com
April 25, 2021
Infinite loop when dispatching redux action
Are you using `postDeviceStatusMetric` in parent of `PaymentSummaryPage.component.tsx` if so the dispatch action re-renders the whole component resulting in the useEffect being triggered again. I'd suggest using the React components extension and use the "highlight when re-render" option. More on reddit.com
🌐 r/reactjs
8
2
November 11, 2024
Infinite loop when dispatching redirect from within a componentWillReceiveProps
Ruthlessly simple bindings to keep react-router and redux in sync - reactjs/react-router-redux More on github.com
🌐 github.com
17
December 29, 2020
Getting infinite loop when using React Context Dispatch in useEffect
I'm working on a project and created a context that is supposed to store my projects data. I included the context dispatch inside of a useEffect in a component which is supposed to pass the data ob... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 67254477 › react-dispatch-going-in-the-infinite-loop
React dispatch going in the infinite loop - javascript
April 25, 2021 - SO AFTER DEBUGGING IT JUST KEEP LOOPING INFINITE - FROM SAGA FUNCTION TO THE SERVICE CALL FUNCTION WHERE ITs been called at SAGA.
🌐
Reddit
reddit.com › r/reactjs › infinite loop when dispatching redux action
Infinite loop when dispatching redux action : r/reactjs
November 11, 2024 - Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help. ... Sorry, this post was deleted by the person who originally posted it. Share ... Are you using `postDeviceStatusMetric` in parent of `PaymentSummaryPage.component.tsx` if so the dispatch action re-renders the whole component resulting in the useEffect being triggered again.
🌐
GitHub
github.com › reactjs › react-router-redux › issues › 212
Infinite loop when dispatching redirect from within a ...
December 29, 2020 - reactjs / react-router-redux Public archive · Notifications · You must be signed in to change notification settings · Fork 632 · Star 7.8k · Copy link · Copy link · Closed · Closed · Infinite loop when dispatching redirect from within a componentWillReceiveProps#212 · Copy link · mattkrick · opened · on Jan 18, 2016 · Issue body actions · if I dispatch a push or replace from within a componentWillReceiveProps, it causes that component to receive new props, making for an infinite loop (at least I think that's the process, chrome profiler stops after the first loop, so I haven't traced it entirely).
Author   mattkrick
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 76185436 › how-to-fix-infinite-loop-caused-by-dispatch-function-in-typescript-react-and-red
reactjs - How to fix infinite loop caused by dispatch function in TypeScript React and Redux code? - Stack Overflow
The list of dependencies must have ... dependencies list is missing values. As an aside, infinite loops are often caused by a missing conditional statement in a useEffect function....
🌐
GitHub
github.com › facebook › react › issues › 9400
Infinite loop when dispatching event in event listener · Issue #9400 · facebook/react
April 11, 2017 - So when the second event is dispatched within the event listener, you get stuck in an infinite loop, because each time dispatch is called, both event listeners get called, then the first one dispatches the second event, so it goes on and on....
Author   kirazbaysal
🌐
GitHub
github.com › reduxjs › redux-thunk › issues › 62
Redux-thunk causing infinite loop in React/Redux application · Issue #62 · reduxjs/redux-thunk
March 22, 2016 - Uncaught RangeError: Maximum call stack size exceeded (anonymous function) @ index.js:10 dispatch @ applyMiddleware.js:44 (anonymous function) @ index.js:12 dispatch @ applyMiddleware.js:44 (anonymous function) @ index.js:12 dispatch @ applyMiddleware.js:44 (anonymous function) @ index.js:12 dispatch @ applyMiddleware.js:44
Author   jbri7357
🌐
GitHub
github.com › facebook › react › issues › 25593
Bug: setState inside useEffect is unreliable in React 18 · Issue #25593 · facebook/react
October 31, 2022 - Even tough setLastRouteCount is the first code that causes a state change in the useEffect, the code in the run() function dispatch a redux action that changes a state that causes the handleResult function (obtained from a hook) to change, causing an infinite loop because lastRouteCount is always with value 0, even tough routeCount has value 1 (I can see when I run console.log). If I comment the line await dispatch... the infinite loop doesn't happen (but it doesn't do what it should). Like in React 17, the state change from setLastRouteCount should happen first (or at least at the same time) than whatever state changes happen later.
Author   lucasbasquerotto
🌐
GitHub
github.com › reduxjs › redux › issues › 1446
Infinite recursion when calling "dispatch" from middleware · Issue #1446 · reduxjs/redux
February 25, 2016 - But, if I call "dispatch(action)" from middleware, it starts calling first middleware and eventually goes into infinite recursion call.
Author   mananvpanchal
Top answer
1 of 2
3

In the current implementation, when your page is rendered, db.collections runs and you set state setUserProfiles(documents) which renders your app and again db.collections runs. to prevent this you should run db.collections in useEffect.

// fetch users only when your app renders
useEffect(() => {
    db.collection("customers")
      .doc(user.info.uid)
      .collection("profiles")
      .get()
      .then((querySnapshot) => {
        const documents = querySnapshot.docs.map((doc) => doc.data());
        setUserProfiles(documents);
      });
  }, []);

have another useEffect

useEffect(() => {
    dispatch(profiles(userProfiles));
  }, [userProfiles]);

this will NOT work neither. setUserProfiles will be causing issue. Because when app renders, you fetch data, you set the state, change the userProfiles, this will rerender app again.

The problem with your code is you do not need setUserProfiles. instead in db.collections() when you get the documents, you dispatch the documents and then access the profiles from redux with useSelector

// fetch users only when your app renders
useEffect(() => {
    db.collection("customers")
      .doc(user.info.uid)
      .collection("profiles")
      .get()
      .then((querySnapshot) => {
        const documents = querySnapshot.docs.map((doc) => doc.data());
        // setUserProfiles(documents); You do not need this
        dispatch(profiles(userProfiles))
      });
  }, []);

Now use useSelector to reach the state in redux

// assuming reducers name is "users"
  const usersState = useSelector((state) => state.users);

now when you use map guard your app

 // make sure you use the correct data
 // you migh need to destructure
 {usersState && usersState.map((profile) => {
2 of 2
0

For anyone that runs into this issue you may find this useful. Following from yilmaz's helpful answer, I had to update the Profiles.js and userSlice.js as follows...

// Profiles.js

export const Profiles = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const usersState = useSelector(profiles);

  useEffect(() => {
    db.collection("customers")
      .doc(usersState.payload.user.user.info.uid)
      .collection("profiles")
      .get()
      .then((querySnapshot) => {
        const documents = querySnapshot.docs.map((doc) => doc.data());
        !usersState.payload.user.user.profiles.includes((arr) =>
          documents.every(arr)
        ) && dispatch(profiles(documents));
      });
  }, []);

  return (
    <div className="profile_container">
      <h1 className="profile_title">Who's Watching?</h1>
      <div className="profile_row">
        {usersState.payload.user.user.profiles.map((profile) => {
          console.log(profile);

          return (
            <div className="profile_individualProfile">
              <img
                src="https://occ-0-300-1167.1.nflxso.net/dnm/api/v6/K6hjPJd6cR6FpVELC5Pd6ovHRSk/AAAABY5cwIbM7shRfcXmfQg98cqMqiZZ8sReZnj4y_keCAHeXmG_SoqLD8SXYistPtesdqIjcsGE-tHO8RR92n7NyxZpqcFS80YfbRFz.png?r=229"
                alt="profile"
              />
              <p>{profile.name}</p>
            </div>
          );
        })}
        <div
          onClick={() => navigate("/add-profile")}
          className="profile_addProfile_container"
        >
          <img
            src="https://img.icons8.com/ios-glyphs/30/FFFFFF/plus--v1.png"
            alt="add profile"
          />
          <h2>Add Profile</h2>
        </div>
      </div>
    </div>
  );
};
// userSlice.js

export const userSlice = createSlice({
  name: "user",
  initialState: {
    user: {
      info: null,
      profiles: [],
    },
  },
  reducers: {
    login: (state, action) => {
      state.user.info = action.payload;
    },
    logout: (state) => {
      state.user.info = null;
    },
    profiles: (state, action) => {
      state.user.profiles.length = 0;

      state.user.profiles.push(...action.payload);
    },
  },
});
🌐
DEV Community
dev.to › webcoderkz › dealing-with-infinite-loops-in-useeffect-hook-j11
Dealing with infinite loops in useEffect hook - DEV Community
February 24, 2020 - "ESLint: React Hook useEffect has missing dependencies: 'body', 'dispatch', 'headers', 'method', 'url', and 'user.jwt'. Either include them or remove the dependency array.(react-hooks/exhaustive-deps)" If we add all of these noted above dependencies, then we would get an infinite loop, because of the headers param is equal to {}. In JavaScript {} === {} is always false, so we would get stuck in a loop.
🌐
GitHub
github.com › reactjs › rfcs › issues › 113
useEffect goes in inifinite loop with React Hooks · Issue #113 · reactjs/rfcs
April 21, 2019 - React/Redux application goes into an infinite loop on using useEffect with object references.. I am trying render pending todos for my application using useEffect.. and passing the array of todos as the second param in useEffect ..but why is not checking the values of the object ? ... const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(RootActions, dispatch) }); const Home = (props) => { const { root, actions } = props; useEffect(() => { getTodos(actions.loadPendingTodo); }, [root.data]); return ( <Segment> <Error {...root } /> <TodoList { ...root } actions={actions} /> </Segment> ); }; export default connect(mapStateToProps, mapDispatchToProps)(Home);
🌐
Stack Overflow
stackoverflow.com › questions › 75598573 › how-to-avoid-infinite-loops-inside-useeffect-working-with-dispatch
How to avoid infinite loops inside useEffect working with dispatch()?
This Could happen when a component repeatedly calls setState inside an useEffect.Because of the dependency it creates an infinite looping. Remove the dependencies from the useEffect and it will work in a perfect manner.