-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReact State Update Issue
More file actions
110 lines (65 loc) · 1.77 KB
/
React State Update Issue
File metadata and controls
110 lines (65 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# ⚠️ React State Update Issue (Async Problem)
## 📌 Problem
When updating state in React using `setState`, the value does **not update immediately**.
Example:
setScale(scale + 0.4)
console.log(scale) // ❌ Still old value
This can cause bugs when trying to use the updated value directly after calling `setState`.
---
## 🧠 Why This Happens
React state updates are **asynchronous**.
React batches multiple updates together for performance reasons, meaning:
- State is scheduled to update
- It does NOT change instantly
- The component re-renders later with the new value
---
## ❌ Common Mistake
Using the current state directly:
setScale(scale + 0.4)
This may use a **stale (old) value**, especially if multiple updates happen quickly.
---
## ✅ Correct Solution
Use the functional update form:
setScale(prev => prev + 0.4)
### ✔ Why this works:
- `prev` always contains the latest state value
- Safe for multiple updates
- Prevents stale state bugs
---
## 🔥 Advanced Usage
If you need to use the updated value immediately:
setScale(prev => {
const newValue = prev + 0.4
// Use newValue here safely
console.log(newValue)
return newValue
})
---
## ⚠️ Important Note
This is especially important in cases like:
- Zoom systems
- Counters
- Animations
- Rapid state updates
---
## 🧪 Example Bug Scenario
setScale(scale + 1)
setScale(scale + 1)
Expected: +2
Actual: +1 ❌
---
## ✅ Fixed Version
setScale(prev => prev + 1)
setScale(prev => prev + 1)
Result: +2 ✅
---
## 🧠 Summary
- React state updates are async
- Never rely on the current state directly when updating
- Always use `prev => ...` when state depends on previous value
---
## 🚀 Best Practice
Always prefer:
setState(prev => newValue)
instead of:
setState(value)