📦 Props (Properties)
Props matlab properties - ye woh data hai jo aap ek component se dusre component mein pass karte ho. Socho jaise aap apne dost ko koi cheez dete ho - woh cheez props hai!
Key Concept: Immutable Data
Definition: Props are read-only and cannot be modified by the component that receives them.
Immutable ka matlab - jo change nahi ho sakta. Jab aapko koi props milta hai, aap use modify nahi kar sakte, sirf read kar sakte ho. Ye React ka important rule hai!
Interactive Props Demo
Neeche ke boxes parent-child relationship dikhate hain:
Data: "Hello from Parent"
Waiting for props...
🕳️ Props Drilling Problem
Jab aapko bahut saare components ke through props pass karne padte hain tab problem hoti hai. Ye drilling jaisi feel hoti hai - jaise zameen mein drill kar rahe ho!
Definition: Props drilling occurs when you need to pass data through multiple intermediate components that don't need the data themselves.
Props Drilling Visualization
Dekho kitne components se data pass ho raha hai jabki sirf last wale ko chahiye!
⚖️ State vs Props
State aur Props mein kya farak hai? Ye React ka sabse important concept hai!
| Feature | Props | State |
|---|---|---|
| Definition | Data passed from parent to child | Data managed within component |
| Mutability | Immutable (change nahi ho sakta) | Mutable (change ho sakta hai) |
| Controlled By | Parent component | Component khud control karta hai |
| Can Change? | No (parent se naya props aaye to yes) | Yes (setState se) |
| Re-render Trigger | Jab parent naye props bheje | Jab setState call ho |
🎯 Local Component State
Local state matlab sirf us component ka apna data. Jaise aapki personal diary - sirf aap hi read aur write kar sakte ho!
Definition: Local state is data that belongs to and is managed by a single component. It's private and fully controlled by that component.
Interactive Counter Demo
Ye counter local state ka example hai - data sirf is component ke andar hai!
✅ Updating State Correctly
State ko update karna aasan hai par sahi tarike se karna zaroori hai! Galat tarike se update kiya to bugs aa sakte hain.
State Update Demo
🎭 Multiple State Updates Batching
React smart hai! Jab aap ek saath bahut saare state updates karte ho, React unhe ek saath batch kar deta hai performance ke liye.
Definition: React groups multiple setState calls into a single re-render for better performance. This is called batching.
Without Batching (Old React)
With Batching (React 18+)
⚠️ Derived State Pitfalls
Derived state matlab - jo state kisi aur state se calculate ho. Ye concept thoda tricky hai aur isme mistakes hona common hai!
Definition: Derived state is state that can be calculated from existing state or props. Creating unnecessary derived state is a common anti-pattern.
🎣 Introduction to Hooks
Hooks React ka game-changer feature hai! Hooks se aap functional components mein state aur lifecycle features use kar sakte ho - class components ki zaroorat nahi!
Definition: Hooks are functions that let you "hook into" React state and lifecycle features from function components.
- ✅ Sirf top level pe call karo (loops/conditions mein nahi)
- ✅ Sirf React functions mein call karo
- ✅ Hook names always "use" se start hote hain
🔧 useState Hook
useState sabse important aur basic hook hai. Isse functional components mein state use kar sakte ho!
Definition: useState is a Hook that lets you add state to functional components. It returns an array with the current state value and a function to update it.
Live useState Demo
⚡ useEffect Hook
useEffect side effects handle karne ke liye hai - jaise data fetching, subscriptions, ya DOM manipulation. Ye class components ke lifecycle methods ka alternative hai!
Definition: useEffect is a Hook that lets you perform side effects in functional components. It runs after every render by default.
useEffect Demo
Timer: 0s
- Dependency array bhoolna (infinite loop ho sakta hai)
- Cleanup function na likhna (memory leaks ho sakte hain)
- Async functions directly useEffect mein use karna
📝 Interview Questions
Q1: What is the difference between Props and State in React?
Props:
- Props are immutable - component receiving props cannot modify them
- Props are passed from parent to child component
- Props are used to pass data and event handlers to child components
- Changes in props cause component to re-render
State:
- State is mutable - component can change its own state using setState
- State is local and private to the component
- State is used for data that changes over time
- Changes in state cause component to re-render
Hinglish: Props parent se aate hain aur change nahi ho sakte, jabki State component ka apna data hai jo change ho sakta hai!
Q2: Explain the concept of "Immutable Data" in React. Why can't we modify props directly?
Immutable data means data that cannot be changed once created. In React, props are immutable because:
Reasons:
- Predictability: Makes component behavior predictable - same props always produce same output
- Debugging: Easier to track where data changes are coming from
- Performance: React can optimize rendering by doing shallow comparisons
- Unidirectional Data Flow: Data flows one way (parent to child), making app logic easier to understand
Wrong:
props.name = "New Name"; ❌Right: Parent component should update the data and pass new props ✅
Hinglish: Props read-only hote hain kyunki isse app ka flow simple rehta hai aur debugging easy ho jati hai!
Q3: What is Props Drilling and how can you solve it?
Props Drilling: When you need to pass data through multiple levels of components, even though intermediate components don't need that data.
Example:
GrandParent → Parent → Child → GrandChildIf only GrandChild needs the data, but we have to pass it through Parent and Child.
Problems:
- Code becomes harder to maintain
- Unnecessary prop passing clutters intermediate components
- Refactoring becomes difficult
Solutions:
- Context API: Share data without passing props explicitly
- Component Composition: Restructure components using children props
- State Management Libraries: Redux, Zustand, Recoil
- Custom Hooks: Encapsulate logic and state
Hinglish: Jab data bahut saare components se pass karna pade tab props drilling problem hoti hai. Solution: Context API ya Redux use karo!
Q4: What are the rules of Hooks? Why do they exist?
Two Main Rules of Hooks:
1. Only Call Hooks at the Top Level
- Don't call Hooks inside loops, conditions, or nested functions
- This ensures Hooks are called in the same order on every render
- Wrong:
if (condition) { useState(0); }❌ - Right: Call at top level, then use condition inside ✅
2. Only Call Hooks from React Functions
- Call from React function components
- Call from custom Hooks
- Don't call from regular JavaScript functions
Why These Rules Exist:
React relies on the order in which Hooks are called to preserve state between renders. If Hook order changes, React can't match state to the correct Hook.
Hinglish: Hooks ko hamesha component ke top pe call karo, loops ya conditions mein nahi. Ye isliye kyunki React Hook order se state track karta hai!
Q5: Explain useState with functional updates. When should you use them?
Functional Updates: When you pass a function to setState instead of a direct value.
Syntax:
setState(prevState => newState)
Example:
// Direct update
setCount(count + 1);
// Functional update
setCount(prevCount => prevCount + 1);
When to Use Functional Updates:
- Multiple updates in same function: Ensures each update uses latest state
- Inside useEffect or callbacks: Avoids stale closure issues
- When new state depends on previous state: Guarantees correct value
Example Problem:
// ❌ This might not work as expected
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
// Result: count + 1 (not count + 3!)
// ✅ This works correctly
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
// Result: count + 3 ✓
Hinglish: Jab state update previous state pe depend kare, to functional update use karo. Ye ensure karta hai ki latest state use ho!
Q6: What is the dependency array in useEffect? Explain different scenarios with examples.
The dependency array controls when useEffect runs. React compares values in the array between renders.
Three Scenarios:
1. No Dependency Array:
useEffect(() => {
console.log("Runs after EVERY render");
});
// Use case: Rarely needed, usually inefficient
2. Empty Dependency Array []:
useEffect(() => {
console.log("Runs ONCE on mount");
// API calls, subscriptions, etc.
}, []);
// Use case: Component initialization, data fetching
3. With Dependencies [dep1, dep2]:
useEffect(() => {
console.log("Runs when count or name changes");
}, [count, name]);
// Use case: React to specific state/prop changes
Important Rules:
- Include ALL values used inside effect that come from component scope
- ESLint plugin helps catch missing dependencies
- Objects/arrays create new references, use useCallback/useMemo if needed
Hinglish: Dependency array ye control karta hai ki effect kab run hoga. Empty array = sirf ek baar, with values = jab wo values change hon!
Q7: What is "Derived State" and why is it considered an anti-pattern? How should you handle it?
Derived State: State that can be calculated/derived from existing state or props.
Anti-pattern Example:
// ❌ BAD: Unnecessary derived state
function UserList({ users }) {
const [userCount, setUserCount] = useState(users.length);
// Problem: userCount won't update when users prop changes!
return <div>Total: {userCount}</div>;
}
Problems:
- Sync Issues: Derived state can become out of sync with source
- Complexity: Need useEffect to keep things in sync
- Bugs: Easy to forget updating derived state
- Performance: Extra state means extra memory and re-renders
Correct Approach:
// ✅ GOOD: Calculate during render
function UserList({ users }) {
const userCount = users.length; // Direct calculation
return <div>Total: {userCount}</div>;
}
// ✅ For expensive calculations, use useMemo
function UserList({ users }) {
const sortedUsers = useMemo(() => {
return users.sort((a, b) => a.name.localeCompare(b.name));
}, [users]);
return <div>{sortedUsers.length} users</div>;
}
Golden Rule: If you can calculate something from props/state, don't store it in state!
Hinglish: Jo cheez props ya state se calculate ho sakti hai, use alag state mein mat rakho. Render time pe calculate karo ya useMemo use karo!
🎓 Key Takeaways
- ✅ Props are immutable and flow from parent to child
- ✅ State is mutable and managed within a component
- ✅ Props drilling can be solved with Context API or state management
- ✅ Always update state correctly using setState, never mutate directly
- ✅ React batches multiple state updates for performance
- ✅ Avoid unnecessary derived state - calculate during render
- ✅ useState adds state to functional components
- ✅ useEffect handles side effects and lifecycle
- ✅ Follow Hook rules: top level only, React functions only
- ✅ Use functional updates when new state depends on previous state
"Props aate hain, State rehta hai! Hooks se sab kuch possible hai!" 🚀