'How to log the updated count value in react?
Why the updated count value is not logged while clicking the button. It always logs the previous count value on button click. Here is the code -
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
function updateCount() {
setCount(count + 1);
console.log(count);
}
return (
<div className="App">
<div>
<p>You clicked {count} times</p>
<button onClick={() => updateCount()}>Show alert</button>
</div>
</div>
);
}
Solution 1:[1]
on react when your state depends on old state value you must update it like this :
function updateCount() {
setCount(oldCount=>oldCount+ 1);
console.log(count);
}
and you must remember updating the state is not instant action it is super fast, but it take few milliseconds
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad |
