Debugging To many rerenders error react redux

Viewed 77

I am experiencing an issue where these lines of code throwing Too many re-renders. React limits the number of renders to prevent an infinite loop error. Can anyone please help me to find out what is causing this issue?

options = useSelector(state => {
        if(!props.disabled) {
            if(props.values) {
                return props.values
            } else if(props.dispatch) {
                dispatch({type: props.dispatch});
                return state[props.getFrom] ? state[props.getFrom] : []
            }
        } else {
            return [];
        }
    }); 

Basically the usecase here is, On component load, I want to call a dispatch where an api will get hit and result will be stored in redux store. Then that values I want to render in dropdown in the same component!

Thanks in advance!

1 Answers

The following line probably causes the component to re render and cause an infinite loop: dispatch({ type: props.dispatch }); maybe you should put that in an effect:

//do not change reference to returning empty array
//  this can cause the component to re render
const EMPTY = [];
const Component = ({ disabled, values, dispatch, getFrom }) => {
  //I assume dispatch does not change and is from
  //  connect or useDispatch
  React.useEffect(() => {
    if (!values && !disabled && dispatch) {
      dispatch({ type: dispatch });
    }
  }, [disabled, dispatch, values]);
  const options = useSelector((state) => {
    if (!disabled && values) {
      return values;
    }
    if(!disabled && state[getFrom]){
      return state[getFrom];
    }
    else {
      return EMPTY;
    }
  });
};
Related