Why does my React component goes into infinite loop?

Viewed 642

I am working on hooking up a simple login page with redux. The problem is it goes into infinite render loop. I am using React hooks and just simply wanted to redirect the page to homepage "/" after successful login attempt.

useEffect(() => {
    if (props.loggedIn === "true") {
      localStorage.setItem("userToken", `Bearer ${props.userToken}`);
      props.history.push("/");
    }
  }, [props.loggedIn])

I am maintaining a loggedIn state in redux and connectingmy component via connect from redux store. After successful attempt, I am setting the loggedIn status to "true". I checked multiple times, there's no issue getting the updated data from redux but as soon as the control comes inside the useEffect, it goes on forever and the error shows:

react_devtools_backend.js:562 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

Looks like a simple issue but I don't know what am I missing here. There is no state change inside the useEffect. I have no idea why that's happening. Searched for some answers, haven't found yet. Any help or pointers in right direction would be very helpful. Thanks in advance.

const mapStateToProps = (state) => {
  return {
    loggedIn: state.user.loggedIn,
    userToken: state.user.userToken
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    login: (userCredentials) => dispatch(userActions.login(userCredentials)),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

1 Answers

Maybe props.history.push re-create(unmount and mount again) the component and it causes to useEffect call again and again. Check the current location of your app.

Something like this props.loggedIn === "true" && props.locatinon.path !== '/' and then your effect code

Related