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

123
Views
How to make setState synchronous in React

A form has multiple inputs, so instead of having a setState function for every input, there is only one, which handles all the events. I tried to use async/await, but I couldn't manage to make it work.

  const [values, setValues] = useState({
    username: undefined,
    password: undefined,
    confirmPassword: undefined,
  });

  //this should be synchronous
  const onChange = (e) => {
    setValues({...values, [e.target.name]: e.target.value});
  }
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use flushSync (https://reactjs.org/docs/react-dom.html#flushsync) to "flush any updates inside the provided callback synchronously".

// Force this state update to be synchronous.
flushSync(() => {
  setValues({...values, [e.target.name]: e.target.value});
});
about 4 years ago · Santiago Trujillo Report

0

I suspect your problem is solved by using the function form of setState, so there is no stale closure for values.

  const onChange = (e) => {
    setValues(values => ({...values, [e.target.name]: e.target.value})) ;
  }
about 4 years ago · Santiago Trujillo 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!