InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
What is the difference between function and class in ReactJS?
The difference between Function and Class in ReactJS:
1: Function Components:
- Are just JavaScript functions.
- Easier and shorter to write.
- Use React Hooks (like useState, useEffect) to manage state and side effects.
- Preferred in modern React.
2: Class Components:
- Use ES6 classes.
- More code and a bit complex.
- Manage state using this.state and lifecycle methods like componentDidMount.
- Were used before Hooks were introduced.
Function Component Example
function Welcome() {
return <h1>Hello from Function Component!</h1>;
}
With State using Hook:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>;
}
Class Component Example
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello from Class Component!</h1>;
}
}
With State:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() =>
this.setState({ count: this.state.count + 1 })}>
Increase
</button>
</div>;
}
}
In summary:
1: Function components are simpler and more modern, while class components are older and more complex. Most new React code uses function components.
2: Function components use simple functions and Hooks for state.
3: Class components use classes, this.state, and lifecycle methods.