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

90
Views
Order of execution upon updating multiple useState

Why is setPeople executed after setFirstName, setEmail and after the event handler is exited?

const [firstName, setFirstName] = useState('');
const [email, setEmail] = useState('');
const [people, setPeople] = useState([]);

const handleSubmit = (e) => {
  e.preventDefault(); // prevent the browser from refreshing the page the moment the form is submitted
  if (firstName && email) {
    const person = { id: new Date().getTime().toString(), firstName, email };

    console.log('before');
    setPeople((people) => {
      console.log('inside');
      return [...people, person]; // append person to the array of people
    });
    console.log('after');
    setFirstName('');  // clear the input fields after clicking submit
    setEmail('');
  }
  console.log('exiting handler');
}

/*
outputs:
  before
  after
  exiting handler
  inside
*/
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This maybe the batching mechanism of react. setState is asynchronous.not always it depends on the execution context. calls can be batched for performance gains.you can check below post ------>

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!