skip to Main Content

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


  1. Your problem is withing this code block:

    <button onClick={handleCurrentquestion(item.iscorrect)} key={index}>{item.option}</button>
    

    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:

    <button onClick={() => handleCurrentquestion(item.iscorrect)} key={index}>{item.option}</button>
    
    Login or Signup to reply.
  2. The problem is onClick={handleCurrentquestion(item.iscorrect)}.
    Most probably, this will solve your problem if your error is not originated in QuestionsResponce:

    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
    Login or Signup to reply.
  3. The error you’re encountering, "Too many re-renders," is likely due to how you’re calling the handleCurrentquestion function within the onClick event handler. When you do onClick={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:

    <button onClick={() => handleCurrentquestion(item.iscorrect)} key={index}>{item.option}</button>
    

    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:

    {QuestionsResponce[currentquestion].Options.map((item, index) => (
      <button onClick={() => handleCurrentquestion(item.iscorrect)} key={index}>
        {item.option}
      </button>
    ))}
    

    This should resolve the "Too many re-renders" error in your React quiz component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search