React State Updates: Asynchronous Behavior

🚀 30 Days — 30 Coding Mistakes Beginners Make Day 5/30 I clicked the button. UI showed: 1 Console showed: 0 😐 Code: setCount(count + 1) console.log(count) I thought React was not updating state… But React state updates are asynchronous. `setState` schedules an update — it does NOT change the value immediately inside the same function. So you are logging the OLD value. Correct place 👇 useEffect(() => { console.log(count) }, [count]) React is not wrong. We were just asking at the wrong time. Day 6 tomorrow 👀 #30DaysOfCode #reactjs #javascript #frontend #webdevelopment #codeinuse

  • graphical user interface

const [count, setCount] = useState(0); console.log("Count value is ", count); I think this will also work because when ever setCount method is used, component re-render, and the passed value to setCount will become the current value of count. And every thing get execute again from top to bottom. Hence, log will print the current value.

Like
Reply

Use prev in handleClick and you won’t have to use useEffect , we should avoid using effect hooks

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories