import { useState } from 'react'
const App = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count);
}
return(
<button onClick={handleClick}>Click Me</button>
)
}
export default App
When I first ran this code and clicked the button, I noticed that the console logged the previous value of count. I always wondered why this happened-because I was updating the state by incrementing it by 1. However, the console didn't show the latest value, only the old one.
But that's not the case - it happens because of re-rendering. In React, re-rendering occurs whenever we update the state value. However, that doesn't mean React re-renders immediately with the new value. Instead, it follows a series of steps.
Whenever React encounters setState(), it schedules a re-render. After all synchronous code has finished executing, React then carries out the re-rendering process. This includes:
- Creating the Virtual DOM with the updated state.
- Comparing it with the previous Virtual DOM (diffing).
- Updating only the necessary parts of the actual DOM (reconciliation).
It's just like a team leader telling a developer:
"Do this task, but only after you finish your current pending work."
So as per our example code:
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count);
}
When we click the button, React encounters setState() and schedules a re-render. It then moves on to the next line: console.log(count). At this moment, the value of count is still 0, so React logs 0 in the console.
After logging, there's no more code left to execute inside the function. Only then does React begin the re-rendering process, and the component is rendered again with the updated value of count.
Conclusion
This is why you see the "previous" value in the console when updating state. React doesn't block execution and update the state immediately - it schedules the update, finishes the current synchronous work, and only then re-renders the component with the new state.
Top comments (0)