Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
React Hooks delayed setState updates causing anomalies in function

I am building a Quiz application using React and I am fetching the questions as an array and maintaining the states:

  1. Array holding all the information about all the questions- statement, options, chosen answer, status(answered, marked for review, unvisited);
  2. object with all information about the current question being displayed
  3. index of current chosen answer (Among the 4 radio buttons)

Now the problem is that when I chose an option and click on 'Save and go to next question' the following events are triggered:

  1. Update current question info (new status and chosen answer)
  2. The array of all questions is updated with the new information for the current question
  3. Go to next question (Update the state #2 (currentQuestionInformation) with the next question and set #3 to the previously chosen answer for that question (if chosen))

Now the problem is that it is very important for these events to be triggered in sequence else when we go to the next question even if we have answered it and come back to it the state #3 is not updated properly.

In my code since I am using react hooks the state updation is asynchronous and I am not getting the right sequence required. The next question function is triggered before the array with the information about all questions is updated. I read a lot of answers but all of them suggested using the Effect Hook. But the main problem is I don't have a generalized use case for the setStates. For example I won't go to the next question necessarily after the total array is updated and this is one particular situation where I need to trigger goToNextQuestion() after state #1 is updated. What should I do to achieve my required goal?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can have a single useState hook that has an object with all those states. When updating, you can then update them all at once.

const [myState, mySetState] = useState({questions:[],current:{},selected:0}

Then when updating, copy the old value, destructuring it and replace with the new info

mySetState({...myState, current:newValue, selected:newSelected})

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!