🚀 React Props & State

Day 9-11: Complete Interactive Guide

📦 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!

// Parent Component function Parent() { const userName = "Raj"; return <Child name={userName} age={25} />; } // Child Component - Props read karna function Child(props) { // ❌ WRONG - Props ko change nahi kar sakte // props.name = "Simran"; // ✅ CORRECT - Sirf read karo return <h1>Hello {props.name}, Age: {props.age}</h1>; }

Interactive Props Demo

Neeche ke boxes parent-child relationship dikhate hain:

Parent Component
Data: "Hello from Parent"
↓
Child Component
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

GrandParent (data: "Top Secret")
↓ props
Parent (doesn't need it)
↓ props
Child (doesn't need it)
↓ props
GrandChild (finally uses it!)

Dekho kitne components se data pass ho raha hai jabki sirf last wale ko chahiye!

⚠️ Problem: Bahut saare unnecessary components ko props pass karna padta hai, code maintain karna mushkil ho jata hai. Solution: Context API ya State Management libraries.

⚖️ 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
// Props Example function Welcome(props) { // props.name change nahi kar sakte return <h1>Welcome {props.name}</h1>; } // State Example function Counter() { const [count, setCount] = useState(0); // State ko change kar sakte hain const increment = () => setCount(count + 1); return <button onClick={increment}>Count: {count}</button>; }

🎯 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

0

Ye counter local state ka example hai - data sirf is component ke andar hai!

function MyComponent() { // Local state - sirf is component ke liye const [name, setName] = useState("Raj"); const [age, setAge] = useState(25); const [isActive, setIsActive] = useState(true); // Ye data bahar accessible nahi hai return ( <div> <p>Name: {name}</p> <p>Age: {age}</p> <p>Status: {isActive ? "Active" : "Inactive"}</p> </div> ); }

✅ 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.

❌ WRONG WAY:
// Direct mutation - Ye GALAT hai! state.count = state.count + 1; // ❌ Never do this state.items.push(newItem); // ❌ Never do this
✅ CORRECT WAY:
// Using setState function const [count, setCount] = useState(0); setCount(count + 1); // ✅ Correct // For arrays - create new array const [items, setItems] = useState([]); setItems([...items, newItem]); // ✅ Correct // For objects - create new object const [user, setUser] = useState({name: "Raj"}); setUser({...user, age: 25}); // ✅ Correct

State Update Demo

Items: []

🎭 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)

function handleClick() { setCount(c => c + 1); // Re-render setFlag(f => !f); // Re-render setName("Raj"); // Re-render // Total: 3 re-renders }

With Batching (React 18+)

function handleClick() { setCount(c => c + 1); setFlag(f => !f); setName("Raj"); // Total: 1 re-render (batched!) }
💡 Pro Tip: React 18+ mein automatic batching hai. Matlab aapko kuch karna nahi padta, React khud optimize kar leta hai!

⚠️ 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.

❌ BAD PATTERN - Unnecessary Derived State:
function UserProfile({ user }) { // ❌ Ye zaroori nahi - directly calculate karo const [fullName, setFullName] = useState( `${user.firstName} ${user.lastName}` ); // Problem: user change hone par fullName sync nahi rahega! return <h1>{fullName}</h1>; }
✅ GOOD PATTERN - Calculate During Render:
function UserProfile({ user }) { // ✅ Directly calculate - no extra state needed const fullName = `${user.firstName} ${user.lastName}`; // Hamesha sync rahega! return <h1>{fullName}</h1>; }
🎯 Rule of Thumb: Agar kuch calculate ho sakta hai existing state/props se, to naya state mat banao. Directly render time pe calculate karo!

🎣 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.

🎯 Rules of Hooks:
  • ✅ 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.

// Basic Syntax const [state, setState] = useState(initialValue); // Examples const [count, setCount] = useState(0); // Number const [name, setName] = useState("Raj"); // String const [isActive, setIsActive] = useState(true); // Boolean const [items, setItems] = useState([]); // Array const [user, setUser] = useState({}); // Object

Live useState Demo

Current State: "Enter a name"
// Functional Updates - Previous state use karna function Counter() { const [count, setCount] = useState(0); const increment = () => { // ✅ Previous state use karo jab multiple updates ho setCount(prevCount => prevCount + 1); }; const addFive = () => { // Ye 5 times correctly increment karega setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); }; return <button onClick={increment}>{count}</button>; }

⚡ 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.

// Basic Syntax useEffect(() => { // Side effect code yahan return () => { // Cleanup code (optional) }; }, [dependencies]); // Example: Document title update function MyComponent() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); // Sirf jab count change ho tab run hoga return <button onClick={() => setCount(count + 1)}>{count}</button>; }

useEffect Demo

Effect Runs: 0 times
Timer: 0s
// Different useEffect Patterns // 1. Run on every render (no dependency array) useEffect(() => { console.log("Har render pe chalega"); }); // 2. Run only once on mount (empty dependency array) useEffect(() => { console.log("Sirf pehli baar chalega"); }, []); // 3. Run when specific values change useEffect(() => { console.log("Jab count change ho"); }, [count]); // 4. Multiple dependencies useEffect(() => { console.log("Jab count YA name change ho"); }, [count, name]); // 5. With cleanup useEffect(() => { const timer = setInterval(() => { console.log("Tick"); }, 1000); // Cleanup - component unmount hone pe return () => clearInterval(timer); }, []);
⚠️ Common Mistakes:
  • 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

Easy

Q1: What is the difference between Props and State in React?

Answer:

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!
Easy

Q2: Explain the concept of "Immutable Data" in React. Why can't we modify props directly?

Answer:

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!
Medium

Q3: What is Props Drilling and how can you solve it?

Answer:

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 → GrandChild
If 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!
Medium

Q4: What are the rules of Hooks? Why do they exist?

Answer:

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!
Medium

Q5: Explain useState with functional updates. When should you use them?

Answer:

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!
Hard

Q6: What is the dependency array in useEffect? Explain different scenarios with examples.

Answer:

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!
Hard

Q7: What is "Derived State" and why is it considered an anti-pattern? How should you handle it?

Answer:

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!" 🚀