Categories
React Answers

How to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React?

Spread the love

Sometimes, we want to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React.

In this article, we’ll look at how to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React.

How to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React?

To fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React, we shouldn’t call state setter functions at the top level of the component.

For instance, instead of writing

const SignInContainer = ({ message, variant }) => {
  const [open, setSnackBarState] = useState(false);
  const handleClose = (reason) => {
    if (reason === "clickaway") {
      return;
    }
    setSnackBarState(false);
  };

  if (variant) {
    setSnackBarState(true);
  }
  return (
    <div>
      <SnackBar
        open={open}
        handleClose={handleClose}
        variant={variant}
        message={message}
      />
      <SignInForm />
    </div>
  );
};

We write

const SignInContainer = ({ message, variant }) => {
  const [open, setSnackBarState] = useState(variant ? true : false);
  const handleClose = (reason) => {
    if (reason === "clickaway") {
      return;
    }
    setSnackBarState(false);
  };

  return (
    <div>
      <SnackBar
        open={open}
        handleClose={handleClose}
        variant={variant}
        message={message}
      />
      <SignInForm />
    </div>
  );
};

We removed the

if (variant) {
  setSnackBarState(true);
}

from the SignInContainer component so that we won’t keep re-rendering the component as we change the open state, which causes an infinite loop.

Conclusion

To fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React, we shouldn’t call state setter functions at the top level of the component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *