Let's now learn React Hooks in this structured way

Great! Let’s now learn React Hooks in this structured way — one at a time — with:
- ✅ Core concept
- 📝 Detailed example (with realistic context)
- 🛠 Best practices
- ⚠️ Pitfalls to avoid
- 📤 Execution order (in lifecycle)
- 🧪 Optional CodeSandbox or timeline example if you want
🔹 Hook #1 — useState
✅ 1. Concept
useState is used to add local state to functional components.
State = data that can change over time (e.g., a count, a form input).
const [value, setValue] = useState(initialValue);
- value: current state
- setValue: function to update state
📝 2. Example: A Counter App
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increase = () => setCount(prev => prev + 1);
const decrease = () => setCount(prev => prev - 1);
const reset = () => setCount(0);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
This component:
- Initializes count to 0
- Updates it using setCount
- React re-renders when count changes
🛠 3. Best Practices
- ✅ Use one state per concept. Don’t jam everything into one object.
- ✅ When new state depends on old:
setState(prev => ...) - ✅ Initial value can be calculated lazily:
const [items, setItems] = useState(() => fetchInitialItems());
⚠️ 4. Common Pitfalls
- ❌ Don’t update state directly:
// Wrong
count++;
setCount(count); // buggy
- ✅ Instead, always use
setCount(prev => prev + 1) - ❌ Avoid asynchronous confusion:
// This won't reflect updated count immediately
console.log(count); // still old
📤 5. Execution Order
| Step | Phase | What Happens |
|---|---|---|
| 1 | Render | useState(0) gives [0, setCount] |
| 2 | Click | setCount(1) triggers re-render |
| 3 | Re-render | count = 1 |
| 4 | DOM updates | React shows Counter: 1 |
Comments (0)
No comments yet. Be the first to comment!

