React · Lesson 86 of 120
Common Mistakes
And fixes.
Every React developer makes the same handful of mistakes. Learn to spot them, and you'll save hours of debugging.
- Same mistakes
- Spot them
- Save hours
Mistakes and fixes
Changing state directly, instead of copying. Using the index as a key in lists that change. Missing dependencies in an effect. Using an effect for a value you could calculate. And calling a handler while rendering, instead of passing it.
| Mistake | Fix |
|---|---|
| items.push(x) | setItems([...items, x]) |
| key={index} | key={item.id} |
| Missing deps | list everything used |
| Effect for derived value | calculate in render |
| onClick={save()} | onClick={save} |
Stale values
Another classic. A timer or effect sees an old value of state, because it captured an old render. Use an updater function, or add the value to the dependencies.
| key | value |
|---|---|
| Symptom | old value |
| Cause | captured render |
| Fix | setX(x => ...) |
| Or | add to deps |
Summary
Copy state, use stable keys, list dependencies, and calculate what you can. Next, best practices.
Key takeaways- Copy, don't change
- Stable keys
- Full deps
Next up: Best Practices — everyday habits