React useState Hook
🔹 React useState Hook
The useState Hook allows you to add state to functional components.
State is data that can change over time and causes the component to re-render when updated.
✅ Importing useState
🧪 Basic Example
📌 Explanation:
| Code | Meaning |
|---|---|
count |
State value |
setCount |
Function to update state |
useState(0) |
Initializes state with value 0 |
🏷️ Updating State
1️⃣ Using New Value Directly
2️⃣ Using Previous State (Recommended)
➡ Best for async updates or multiple state changes.
🎯 Multiple States in One Component
You can use useState more than once:
📌 Using Objects in State
⚠ Always use the spread operator to avoid overwriting the object.
📌 Using Arrays in State
⏳ Initial Value with a Function (Optimization)
Useful for heavy computations:
⚠ Important Notes
✔ State updates are asynchronous
✔ Updating state triggers a component re-render
✔ Never modify state directly:
❌ Wrong:
🎉 Summary Table
| Feature | Description |
|---|---|
| Adds state to functional components | ✔ |
Returns array [value, updater] |
✔ |
| Can be used multiple times | ✔ |
| Works with strings, numbers, objects, arrays | ✔ |
