infinite loop when dispatching in componentWillReceiveProps infinite loop when dispatching in componentWillReceiveProps reactjs reactjs

infinite loop when dispatching in componentWillReceiveProps


Try adding a condition to compare the props. If your component needs it.

componentWillRecieveProps(nextProps){ if(nextProps.value !== this.props.value)  dispatch(action()) //do dispatch here }


Your componentWillReceiveProps is in an infinite loop because calling fetchUser will dispatch an action that will update the Props.

Add a comparison to check if the specific prop changes before dispatching the action.EDIT:

In React 16.3+ componentWillReceiveProps will be slowly deprecated.

It is recommended to use componentDidUpdate in place of componentWillReceiveProps

componentDidUpdate(prevProps) {  if (this.props.params.username !== prevProps.params.username) {    dispatch(fetchUser(username));  }}

See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change


If you have react routes with some path params like profile/:username, You can simply compare the props.location.pathname

componentWillReceiveProps(nextProps){        if(nextProps.location.pathname !== this.props.location.pathname){          dispatch()        } }