In React, there are two types of components: class components and function components.
Class components are created by extending the React.Component class and defining a render() method that returns the UI elements to be rendered. They are typically used for more complex components that need to manage state and handle events.
Here's an example of a class component:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default MyComponent;
Function components are created by defining a JavaScript function that returns the UI elements to be rendered. They are typically used for simpler components that don't need to manage state or handle events.
Here's an example of a function component:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}
export default MyComponent;
Note that function components use the useState hook to manage state, whereas class components use the this.state object. Also, event handlers in function components are declared as regular functions, whereas they are declared as arrow functions in class components to bind the this context.