React.Component
.π Example of a Simple Class Component
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <h2>Welcome to React Class Components!</h2>;
}
}
export default Welcome;
Before React Hooks (useState
, useEffect
), class components were the only way to use state and lifecycle methods. They are still used in:
React
and Component
All class components must extend React.Component
.
π Example: Message.js
Class Component
import React, { Component } from "react";
class Message extends Component {
render() {
return <h2>This is a Class Component!</h2>;
}
}
export default Message;
Step 2: Import and Use in App.js
import Message from "./Message";
function App() {
return (
<div>
<Message />
</div>
);
}
export default App;
Props allow class components to receive dynamic data from parent components.
π Example: Class Component with Props
import React, { Component } from "react";
class Greeting extends Component {
render() {
return <h2>Hello, {this.props.name}!</h2>;
}
}
export default Greeting;
Using Props in App.js
import Greeting from "./Greeting";
function App() {
return (
<div>
<Greeting name="Zia" />
</div>
);
}
export default App;
State is internal data that a component can manage and update.
π Example: Counter Class Component with state
import React, { Component } from "react";
class Counter extends Component {
constructor() {
super();
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>Increase</button>
</div>
);
}
}
export default Counter;
Using the Counter Component in App.js
import Counter from "./Counter";
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
Lifecycle methods allow you to control behavior at different stages of a component’s existence.
componentDidMount()
→ Runs after the component is first rendered.componentDidUpdate()
→ Runs when state or props change.componentWillUnmount()
→ Runs before the component is removed.π Example: Using componentDidMount()
import React, { Component } from "react";
class DataFetcher extends Component {
componentDidMount() {
console.log("Component has mounted!");
}
render() {
return <h2>Check the console for lifecycle logs!</h2>;
}
}
export default DataFetcher;
Feature | Class Component | Functional Component |
---|---|---|
State Management | Uses this.state and setState() |
Uses useState Hook |
Lifecycle Methods | Uses methods like componentDidMount() |
Uses useEffect Hook |
Code Complexity | More complex | Simpler and cleaner |
Performance | Slightly heavier | More optimized |
Modern Usage | Used in older projects | Preferred in new projects |
β
Always extend React.Component
when creating class components.
β
Use constructor()
only when state initialization is needed.
β
Use setState()
instead of modifying state directly.
β
Avoid deeply nested state to keep the component simple.