Why is my React state not updating immediately after calling setState?

clock icon

asked 73 days ago

message icon

0

eye icon

18

I’m trying to update a counter in React using useState, but the value doesn’t update immediately after calling setCount.

Here’s my code:

1import React, { useState } from "react";
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 const handleClick = () => {
7 setCount(count + 1);
8 console.log("Count after update:", count); // Always logs the old value
9 };
10
11 return (
12 <div>
13 <p>Current count: {count}</p>
14 <button onClick={handleClick}>Increase</button>
15 </div>
16 );
17}
18
19export default Counter;
1import React, { useState } from "react";
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 const handleClick = () => {
7 setCount(count + 1);
8 console.log("Count after update:", count); // Always logs the old value
9 };
10
11 return (
12 <div>
13 <p>Current count: {count}</p>
14 <button onClick={handleClick}>Increase</button>
15 </div>
16 );
17}
18
19export default Counter;

When I click the button, the <p> updates correctly on the UI, but the console.log always shows the previous value instead of the new one.

Question:

  • Why does console.log not show the updated state immediately after calling setCount?
  • How can I correctly log the updated state value after it changes?

0 Answers

Empty state illustration

No Answers Found

The answer board is empty. Make it rain with your brilliant answer.

1

Write your answer here

Top Questions

Popular Tags