1. JSX - JavaScript XML
Kya hai JSX? JSX ek syntax extension hai JavaScript ka, jo aapko HTML jaisa code likhne deta hai JavaScript files mein. Yeh React ka ek powerful feature hai jo UI ko describe karna bahut easy banata hai.
Why JSX Exists?
React mein JSX use karne ke main reasons:
- Readability: HTML-like syntax samajhna easy hai
- Type Safety: Compile time pe errors catch kar sakte hain
- JavaScript Power: Full JavaScript features use kar sakte hain
- Performance: Babel compile karte waqt optimize kar deta hai
Important: JSX optional hai, but React community mein yeh standard practice hai kyunki yeh code ko clean aur maintainable banata hai.
JSX Transformation
🔄 JSX to JavaScript Transformation
JSX Code
Compiled JavaScript
const element = (
<div className="container">
<h1>Hello, React!</h1>
<p>Welcome to JSX</p>
</div>
);
const element = React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', null, 'Hello, React!'),
React.createElement('p', null, 'Welcome to JSX')
);
JSX Rules & Pitfalls
✅ Correct JSX
// Single parent element
return (
<div>
<h1>Title</h1>
<p>Content</p>
</div>
);
❌ Wrong JSX
// Multiple parent elements
return (
<h1>Title</h1>
<p>Content</p>
);
Important Rules:
classNameuse karo,classnahi (JavaScript reserved word hai)- All tags ko close karna zaroori hai:
<img />,<br /> - camelCase property names:
onClick,backgroundColor - JavaScript expressions
{}mein wrap karo - Comments:
{/* yeh comment hai */}
2. React Components
Components kya hain? Components React applications ke building blocks hain. Yeh reusable, independent pieces hain jo apna khud ka logic aur UI maintain karte hain.
Functional vs Class Components
📊 Component Comparison
Why Functional Components Today?
- Simplicity: Less boilerplate code
- Hooks: State aur lifecycle features easily use kar sakte hain
- Performance: Lightweight aur faster
- Testing: Test karna easy hai
- Future: React team ka focus functional components pe hai
3. Component Re-rendering Cycle
Re-rendering kab hoti hai? Jab component ka state ya props change hote hain, tab React us component ko re-render karta hai.
🔄 Live Re-rendering Demo
Render Count: 0
Re-rendering Triggers
1. State Change: setState ya useState hook se state update
2. Props Change: Parent se nayi props milna
3. Parent Re-render: Parent component re-render hone pe child bhi
4. Context Change: Context value update hone pe
5. Force Update: forceUpdate() method (avoid karna chahiye)
Performance Tip: Unnecessary re-renders se bachne ke liye React.memo, useMemo, aur useCallback hooks use karo.
4. Component Composition
Composition ka matlab: Chhote components ko combine karke bade components banana. Yeh React ka ek fundamental pattern hai.
🧩 Composition Example
// Base Button Component
function Button({ children, onClick, type }) {
return (
<button className={`btn btn-${type}`} onClick={onClick}>
{children}
</button>
);
}
// Dialog Component using Button
function Dialog({ title, message, onConfirm, onCancel }) {
return (
<div className="dialog">
<h2>{title}</h2>
<p>{message}</p>
<Button type="primary" onClick={onConfirm}>
Confirm
</Button>
<Button type="secondary" onClick={onCancel}>
Cancel
</Button>
</div>
);
}
Benefits of Composition:
- Code reusability badhti hai
- Maintenance easy ho jata hai
- Testing individual components ki asaan hai
- Flexibility milti hai design changes ke liye
5. Passing Functions Between Components
Functions as Props: React mein parent component se child component ko functions pass kar sakte hain. Isse child parent ko update kar sakta hai.
📤 Parent-Child Communication Demo
// Parent Component
function Parent() {
const [message, setMessage] = useState('');
const handleChildMessage = (msg) => {
setMessage(msg);
console.log('Child ne bheja:', msg);
};
return (
<div>
<h2>Parent: {message}</h2>
<Child onSendMessage={handleChildMessage} />
</div>
);
}
// Child Component
function Child({ onSendMessage }) {
return (
<button onClick={() => onSendMessage('Hello Parent!')}>
Send Message
</button>
);
}
Default Props & PropTypes
import PropTypes from 'prop-types';
function UserCard({ name, age, email, role }) {
return (
<div className="user-card">
<h3>{name}</h3>
<p>Age: {age}</p>
<p>Email: {email}</p>
<p>Role: {role}</p>
</div>
);
}
// PropTypes for type checking
UserCard.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
email: PropTypes.string,
role: PropTypes.oneOf(['admin', 'user', 'guest'])
};
// Default props
UserCard.defaultProps = {
email: 'Not provided',
role: 'guest'
};
PropTypes ka fayda: Development mein wrong type ke props pass hone pe warning milti hai. Production mein yeh check nahi hota performance ke liye.
🎯 Interview Questions
Q1.
What is JSX and why do we use it in React? Can you write React code without JSX?
Easy
Answer:
JSX (JavaScript XML) is a syntax extension for JavaScript that allows us to write HTML-like code in JavaScript files.
Why we use JSX:
Yes, you can write React without JSX: You can use React.createElement() directly, but it's verbose and less readable.
JSX (JavaScript XML) is a syntax extension for JavaScript that allows us to write HTML-like code in JavaScript files.
Why we use JSX:
- More readable and intuitive than React.createElement()
- Easier to visualize UI structure
- Compile-time error checking
- Better developer experience
Yes, you can write React without JSX: You can use React.createElement() directly, but it's verbose and less readable.
Q2.
Explain the difference between Functional and Class components. Why are Functional components preferred today?
Easy
Answer:
Class Components:
Functional Components:
Why Functional Components are preferred:
Class Components:
- Use ES6 class syntax
- Have lifecycle methods (componentDidMount, etc.)
- Use this.state and this.setState
- More boilerplate code
Functional Components:
- Simple JavaScript functions
- Use Hooks for state and lifecycle (useState, useEffect)
- No 'this' binding issues
- Cleaner and more concise
Why Functional Components are preferred:
- Easier to read, test, and debug
- Better performance (less overhead)
- Hooks provide more flexibility than lifecycle methods
- React team's official recommendation
- Easier to extract custom logic into custom hooks
Q3.
What triggers a component to re-render in React? How can you optimize unnecessary re-renders?
Medium
Answer:
Re-render Triggers:
Optimization Techniques:
Re-render Triggers:
- State change: When setState/useState updates state
- Props change: When parent passes new props
- Parent re-render: Child components re-render by default
- Context change: When Context value updates
- forceUpdate(): Manual trigger (should be avoided)
Optimization Techniques:
- React.memo(): Memoize functional components
- useMemo(): Memoize expensive calculations
- useCallback(): Memoize functions
- Key prop: Proper key usage in lists
- Code splitting: Lazy loading with React.lazy()
- Avoid inline functions: In JSX props
Q4.
Explain component composition in React. How is it different from inheritance?
Medium
Answer:
Component Composition: Building complex UIs by combining simpler, reusable components. React recommends composition over inheritance.
Composition Patterns:
Why Composition over Inheritance:
Example: Instead of creating ButtonBase class and extending it, create a Button component and compose it with different props and children.
Component Composition: Building complex UIs by combining simpler, reusable components. React recommends composition over inheritance.
Composition Patterns:
- Containment: Using children prop to nest components
- Specialization: Creating specific versions of generic components
- Props-based composition: Passing components as props
Why Composition over Inheritance:
- More flexible and reusable
- Easier to understand and maintain
- Avoids deep inheritance hierarchies
- Better separation of concerns
- React doesn't recommend using inheritance for component reuse
Example: Instead of creating ButtonBase class and extending it, create a Button component and compose it with different props and children.
Q5.
How do you pass data from child component to parent component? Explain with an example.
Medium
Answer:
In React, data flows from parent to child via props. To send data from child to parent, we pass a callback function from parent to child.
Pattern:
Example:
In React, data flows from parent to child via props. To send data from child to parent, we pass a callback function from parent to child.
Pattern:
- Parent creates a function
- Parent passes this function to child as a prop
- Child calls this function with data as argument
- Parent receives and processes the data
Example:
// Parent
function Parent() {
const handleData = (data) => {
console.log('Received from child:', data);
};
return <Child onSendData={handleData} />;
}
// Child
function Child({ onSendData }) {
return (
<button onClick={() => onSendData('Hello Parent')}>
Send to Parent
</button>
);
}
Q6.
What are PropTypes and defaultProps? Why are they important? Are they still used in modern React?
Medium
Answer:
PropTypes: A type-checking mechanism for component props. It validates that components receive props of the correct type.
defaultProps: Specifies default values for props when they're not provided by the parent.
Importance:
Modern Usage:
Example:
PropTypes: A type-checking mechanism for component props. It validates that components receive props of the correct type.
defaultProps: Specifies default values for props when they're not provided by the parent.
Importance:
- Catches bugs early in development
- Documents component API
- Improves code reliability
- Provides runtime warnings
Modern Usage:
- Still used but less common
- TypeScript is preferred for type checking
- PropTypes run only in development mode
- Default parameters in function components replace defaultProps
Example:
// With PropTypes
Button.propTypes = {
text: PropTypes.string.isRequired,
onClick: PropTypes.func
};
Button.defaultProps = {
onClick: () => {}
};
// Modern approach with default parameters
function Button({ text, onClick = () => {} }) {
return <button onClick={onClick}>{text}</button>;
}
Q7.
Explain the Virtual DOM and how React's reconciliation algorithm works during re-rendering.
Hard
Answer:
Virtual DOM: A lightweight JavaScript representation of the actual DOM. React maintains this in-memory copy for efficient updates.
Reconciliation Process:
Diffing Algorithm:
React Fiber (Modern Architecture):
Why it's efficient: Batch updates, minimal DOM manipulation, and intelligent diffing make React fast even for complex applications.
Virtual DOM: A lightweight JavaScript representation of the actual DOM. React maintains this in-memory copy for efficient updates.
Reconciliation Process:
- Render Phase: React creates a new Virtual DOM tree
- Diffing: Compares new Virtual DOM with previous one
- Commit Phase: Updates only changed parts in real DOM
Diffing Algorithm:
- Element Type: If element type changes, entire subtree is replaced
- Attributes: Only changed attributes are updated
- Keys in Lists: Uses keys to identify which items changed
- Component Type: Same type components maintain state across renders
React Fiber (Modern Architecture):
- Breaks rendering into chunks
- Can pause and resume work
- Prioritizes urgent updates
- Better performance for complex UIs
Why it's efficient: Batch updates, minimal DOM manipulation, and intelligent diffing make React fast even for complex applications.