[Solved] Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop - React JS
In React JS app, sometimes we got "Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop". But do you know why this has happened. In fact it is caused by various errors. Now we try to understand what this error actually means us. It means that our component is being rendered at infinite time. Now a question may come to mind, why our component is being rendered at infinite time. The reason is that our state immediately change when our component is rendered. And we know that when state change our component will be rendered again. So It makes infinite loop.
Previously we know that this error occurs lots of reasons. So first need to identify your mistake and then try to solve this mistake. Now I am trying to give some example to better understand about this.
Example 1.
<button onClick={setToggle(!toggle)}>{ toggle ? 'Close' : 'Open' }</button>
In this scenario, we need to bind callback function for solve.
Example 2.
const [msg, setMsg] = useState('Please open!!!');
const [toggle, setToggle] = useState(false);
if (msg) {
setToggle(true)
}
We can solve different way,
const [toggle, setToggle] = useState(msg ? true : false);
OR
const [toggle, setToggle] = useState(!!msg);
OR
useEffect(() => {
if (msg) {
setToggle(true)
}
}, []);
Hope this solution will solve your problem. To learn more about react, you can check The complete React developer course w/Hooks & Redux course.