2

The doubt is , in the webpage the value gets incremented and displays but in console it displays the previous value......what am i not understanding ?

when i click on the button , in the webpage the value gets incremented but whereas at the console output it's still the previous value :/

function App() {
  function handleClick()
  {
 
    setValue((prev)=>prev+1)
    console.log(value)

  }
  const [value,setValue]=useState(0);
  return (

    <div className="App" style={{fontSize:"100px"}}>
      {value}
      <button onClick={handleClick}>increment</button>
    </div>
  );
}

export default App;
John Mellow
  • 116
  • 5

1 Answers1

5

This is beacause setValuse is async function, and value in state will be update in next renderer.

Check this:

  function handleClick()
  {
 
    setValue((prev)=>prev+1)
    console.log(value)

  }
  const [value,setValue]=useState(0);
  
  useEffect(() => { console.log(value)}, [value])

Sharpek
  • 658
  • 4
  • 5
  • so, all the hooks are async functions ? or just useState ? – John Mellow Jan 16 '22 at 08:10
  • 1
    Hooks it's a normal function, and everything it's depends on what kind of hook you use. setState is async function because of how react state works ;) – Sharpek Jan 16 '22 at 08:13