Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Components are building blocks of React application. They can be:
React.Component| Functional components | Class components | |
|---|---|---|
| Syntax | function MyComponent() | class MyComponent extends React.Component |
| State support | Yes (via useState, useReducer) | Yes (via this.state) |
| Lifecycle | Through hooks (useEffect) | Methods (componentDidMount, etc.) |
| Context | useContext() | this.context |
| this | No this | Uses this |
| Code brevity | shorter and simpler | more verbose |
| Hooks support | Yes | No |
| Performance (theoretically) | Slightly higher | Slightly lower |
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component rendered");
return () => {
console.log("Component unmounted");
};
}, []);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
import React from "react";
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log("Component rendered");
}
componentWillUnmount() {
console.log("Component unmounted");
}
render() {
return (
<div>
<p>Counter: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
+
</button>
</div>
);
}
}