Answers for "Too many re-renders. React limits the number of renders to prevent an infinite loop."

3

too many re-renders. react limits the number of renders to prevent an infinite loop.

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

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

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}
Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}
Comprehensive Demo
See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.
Posted by: Guest on March-09-2021
0

Too many re-renders. React limits the number of renders to prevent an infinite loop.

Perhaps you are setting state directly in component function.
Instead you could use useEffect hook to wrap it and give some dependencies.
Posted by: Guest on October-18-2021

Code answers related to "Too many re-renders. React limits the number of renders to prevent an infinite loop."

Code answers related to "Javascript"

Browse Popular Code Answers by Language