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

111
Views
React hook is not setting my state at time
const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);

    useEffect(()=>{
    
      
        },[numbers,aNumber])

const printNumbers = ()=>{
setNumbers({...numbers, number2:aNumber});
console.log(numbers);
}

return (
<>
<button onClick={printNumbers}>print a number <button/>
</>

) 

when i click on the button in the console it will print {number1: 2, number2: 0} But i want it to print {number1: 2, number2: 1} but it looks like react not update mi hook correrctly, but... when a click another time in the button it prints {number1: 2, number2: 1}, but i need it in the first click, how can i fix it?

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

0

You set the console log inside the printNumbers function. Since the state update is async, you'd have to put the console.log inside the useEffect to be notified after an update. Something similar to:

useEffect(()=>{
   console.log(numbers);
},[numbers,aNumber])

const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);

const printNumbers = ()=>{
   setNumbers({...numbers, number2:aNumber});
}
about 4 years ago · Juan Pablo Isaza Report

0

In React, state updates are asynchronous and batched. setState is not guaranteed to run (and in practice, new values will never be available) before the proceeding code. To solve this, use a local variable to retain a copy of the new state which you can both dispatch with your setState, and log immediately:

const printNumbers = () => {
  const newNumbers = { ...numbers, number2: aNumber };
  setNumbers(newNumbers);
  console.log(newNumbers);
}
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!