I have developed a simple react quiz but I get following error after displaying score : "Too many re-renders. React limits the number of renders to prevent an infinite loop."
import React, { useState } from 'react'
import {QuestionsResponce} from "./constants/utils";
const Quizz = () => {
const[currentquestion, setCurrentquestion]=useState(0);
const[score,setScore]=useState(0);
const handleCurrentquestion=(iscorrect)=>{
if(iscorrect===true){
setScore(score+1);
}
const nextquestion=currentquestion+1;
if(nextquestion < QuestionsResponce.length){
return setCurrentquestion(nextquestion)
}
}
return (
<div className="quiz-container">
<h1>Question{currentquestion+1}/{QuestionsResponce.length}</h1>
<h1>{QuestionsResponce[currentquestion].Question}</h1>
<div className="option-section">
{QuestionsResponce[currentquestion].Options.map((item,index)=>
<button onClick={handleCurrentquestion(item.iscorrect)} key={index}>{item.option}</button>
)}
</div>
{score}
</div>
)
}
export default Quizz
I’ve tried to use the useEffect()
hook to handle the error but no luck.
3
Answers
Your problem is withing this code block:
You have to pass a callback to
onClick
and not a function call, otherwise that function will be called immediately and triggers a render which will call the function again and again, resulting in an infinite loop.Replace the line above by:
The problem is
onClick={handleCurrentquestion(item.iscorrect)}
.Most probably, this will solve your problem if your error is not originated in
QuestionsResponce
:The error you’re encountering, "Too many re-renders," is likely due to how you’re calling the
handleCurrentquestion
function within theonClick
event handler. When you doonClick={handleCurrentquestion(item.iscorrect)}
, it calls the function immediately instead of waiting for the button click.You can fix this by using an arrow function to call
handleCurrentquestion
with the parameter, like this:By wrapping the
handleCurrentquestion
call in an arrow function, you ensure it’s only called when the button is clicked, preventing the excessive re-renders.Here’s the modified code snippet:
This should resolve the "Too many re-renders" error in your React quiz component.