Interview question
What are React components? Explain functional and class components. React components क्या हैं? Functional और class components explain करें।
Answer
Components are reusable pieces of UI. React has two types: Functional Components (functions returning JSX) and Class Components (ES6 classes).
| Aspect | Functional Component | Class Component |
|---|---|---|
| Definition | JavaScript function | ES6 class extending React.Component |
| State | useState hook | this.state |
| Lifecycle | useEffect hook | componentDidMount, etc |
| Simplicity | Simpler, preferred modern | More verbose |
| Performance | Better with hooks | Slightly heavier |
// Functional Component (Modern)
function Welcome() {
return <h1>Hello, World!</h1>;
}
// With arrow function
const Welcome = () => {
return <h1>Hello, World!</h1>;
};
// Or shorter
const Welcome = () => <h1>Hello, World!</h1>;
// Class Component (Legacy)
class Welcome extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
// Using components
function App() {
return (
<div>
<Welcome />
<Welcome />
</div>
);
}
// With parameters
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
<Greeting name='John' />
<Greeting name='Jane' />
// Default export
export default Welcome;// Functional Component
function Welcome() {
return <h1>Hello</h1>;
}
// Arrow function
const Welcome = () => <h1>Hello</h1>;
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
}
// Functional अब preferred है
// Hooks से state और lifecycle use कर सकते हैंWas this answer clear?