Uncaught Invariant Violation: 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.
"Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."
The problem can be found in your onClick
prop:
<button className="previous-round" onClick={setOrderData_(previous(orderData_))}>‹</button>
^
Everything between the curly braces gets evaluated immediately. This causes the setOrderData_
function to be called in every render loop.
By wrapping the function with an arrow function, the evaluated code will result in a function that can be called whenever the user clicks on the button.
<button className="previous-round" onClick={() => setOrderData_(previous(orderData_))}
>‹</button>
You can find more information about JSX and expressions in the official docs
https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx
The reason for the infinite loop is because something (most likely setState
) in the event callback is triggering a re-render. This will call the event callback again and causes React to stop and throw the 'Too many re-renders.' error.
To better understand the reason why JSX works this way see the code below. JSX is actually being compiled to Javascript and every prop will be passed to a function in an Object. With this knowledge, you will see that handleEvent()
is being called immediately in the last example.
// Simple example
// JSX: <button>click me</button>
// JS: createElement('button', { children: 'click me' })
createElement("button", { children: "click me" });
// Correct event callback
// JSX: <button onClick={handleClick}>click me</button>
// JS: createElement('button', { onClick: handleClick, children: 'click me' })
createElement("button", { onClick: handleClick, children: "click me" });
// Wrong event callback
// JSX: <button onClick={handleClick()}>click me</button>
// JS: createElement('button', { onClick: handleClick(), children: 'click me' })
createElement("button", { onClick: handleClick(), children: "click me" });
Too many re-renders. React limits the number of renders to prevent an infinite loop. Next js error
You might want to put your code inside useEffect like so and use router instance from nextJS to get pathName.
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
import { useState,useEffech } from "react";
import { useRouter } from 'next/router';
function MyApp({ Component, pageProps }) {
const [navbar, Setnavbar] = useState(0);
const router = useRouter()
const params= router.pathname
useEffect(()=>{
if (process.browser) {
if (params == "/about") {
Setnavbar(0);
}
else if (params == `/id/portal`) {
Setnavbar(1);
}
}
},[params])
How do I resolve Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop while setting a state?
It seems you are running the code as an unintentional side effect and the condition is malformed.
Use the useEffect
hook with correct dependencies to issue the side-effect to update state.
Example:
useEffect(() => {
if (location.state !== null) {
setcompanyOneAlready(location.state.name.companyName);
}
}, [location.state]);
To help save a rerender you can also check the current companyOneAlready
value prior to enqueueing the state update.
useEffect(() => {
if (location.state?.name?.companyName !== companyOneAlready) {
setcompanyOneAlready(location.state.name.companyName);
}
}, [location.state, companyOneAlready]);
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop - ProtectedRoutes Component
Yow problem Is heaw.
export default function ProtectedRoutes({component: Component, ...rest}) {
const [auth, setAuth] = useState(false);
//get cookie from browser if logged in
const token = cookies.get("TOKEN");
if (token) {
setAuth(true);
};
return auth ? <Component /> : <Navigate to="/" />
}
You need yo put setAuth
in a useEffect
export default function ProtectedRoutes({component: Component, ...rest}) {
const [auth, setAuth] = useState(false);
React.useEffect(()=>{
const token = cookies.get("TOKEN");
if (token) {
setAuth(true);
}
},[auth]);
return auth ? <Component /> : <Navigate to="/" />
}
Related Topics
Convert Date/Time in Gmt to Est in JavaScript
Retaining the Textbox Values Even After Refresh
How to Get Full Path of Selected File on Change of <Input Type='File'> Using Javascript, Jquery-Ajax
Prevent React-Router History.Push from Reloading Current Route
How to Trigger Change of Option in Dropdown When Options Can Have Same Value
Convert Milliseconds to Hours and Minutes Using Momentjs
Observe Localstorage Changes in Js
Append Data to Json Array Issue
Hide Div If Value Is Blank (Javascript)
Dynamically Add Variable Name Value Pairs to Json Object
Add Two Numbers and Display Result in Textbox With JavaScript
How to Hide Select Options With Javascript (Cross Browser)
React Jsx - Make Substring in Bold
How to Hide Div When You Scroll to Bottom and Show It Again When Scroll Up to Top
How to Pass Array Variable from View to Controller in Spring MVC
Close Window Automatically After Printing Dialog Closes
Typescript | Warning About Missing Return Type of Function, Eslint