React Quiz App: Issue with Displaying Correct Score on Quiz Completion

Question:

I am currently working on a React quiz app where users can answer multiple-choice questions and receive feedback on their answers. The app is functioning well for the most part, but I am encountering an issue with the final score display when the quiz is completed.

Here is the relevant portion of the code:

// ... (Rest of the imports)

function App() {
  // ... (State variables and initializations)

  const handleSubmission = () => {
    if (selectedOption === questions[currentQuestionIndex].correct && currentQuestionIndex < questions.length - 1) {
      setScore((prevScore) => prevScore + 1);
      setFeedback('Correct!');
    } else {
      setFeedback('Incorrect!');
    }

    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    } else {
      setFeedback(`Quiz Complete! You scored ${score} out of ${questions.length}!`);
    }
  };

  // ... (Rest of the component)

  return (
    <div style={style.container}>
      {/* ... (JSX structure) */}
    </div>
  );
}

export default App;

The issue arises when the quiz is completed, and the final feedback displays an incorrect score, even if all the answers were correct. I suspect this is due to the asynchronous nature of the setScore function.

I’ve tried incorporating the useEffect hook to update the feedback after the score changes, and also using the state update callback in setScore, but the problem persists.

Any insights into resolving this issue and ensuring that the final score is accurately displayed would be greatly appreciated.