0
export default function Test() {
const [steps, setSteps] = useState(0);

function increment() {
setSteps(steps=>steps+2);
console.log(steps)
  if(steps==2)//doesnot go in if
  {

  }
}

return (
<div>
  Today you've taken {steps} steps!
  <br />
  <button onClick={increment}>
    step
  </button>
</div>
);
}

after updating state i am not getting updated value in console and doesnot go in if statement as well. what am i doing wrong its being correctly shown in web page

jk123
  • 13
  • 4
  • https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Robert May 29 '21 at 08:52
  • `setSteps(steps=>steps+2)` change to `setSteps(steps + 2)` and it should work. – ulou May 29 '21 at 08:56
  • no, same issue again – jk123 May 29 '21 at 09:00
  • @jk123 is the same issue.... Just setState is async method so it will be executed in nearly future of component life cycle. If you need react on steps change you have to use useEffect and in dependency array pass steps state, then in this function you can check if is equal 2. – Robert May 29 '21 at 09:36

0 Answers0