Search code examples
reactjsreduxinfinite-loopuse-effectdispatch

react redux lead to infinite loop while using useeffect and dispatch


I deleted my initial question because it was not very well explained from my side and led to unnecessary discuission and lost focus.

I am trying to build an app with react and redux and got stuck in an infinite loop while using useEffect and dispatch.

I build a codesandbox to reproduce the issue. Here is my work. https://codesandbox.io/s/suspicious-morning-ew161 It seems like the issue is somehow related to line 8 in App.js but I can't explain why and how.


Solution

  • You should not write useSelector calls like that. See https://react-redux.js.org/api/hooks#equality-comparisons-and-updates

    Instead of

    const { auth } = useSelector((state) => ({ ...state }));
    

    write

    const auth = useSelector((state) => state.auth);
    

    Your other problem is

                  component={(props) => (
                    <TestProfilePage {...props} key={props.match.params.user_id} />
                  )}
    

    this will create a new component on every rerender and React will unmount the full component tree and create a new one, effectively re-running your useEffect. Instead of component, use render. Also see the react-router docs on that.

    Your code does two things:

    • it returns a new object on every selector call, which will make your component rerender always, even if there is no state change
    • it returns the full state, so even if you just returned state without the spread, it would rerender at any state change.