About Lesson
What is React Components?
In React.js, components are the building blocks of a React application. They allow you to break the UI into independent, reusable pieces and think about each piece in isolation. Here’s an overview of components in React:
Types of Components:
a. Functional Components
- Functions that return JSX.
- Simpler and easier to write.
- Use React hooks (e.g., useState, useEffect) for state and lifecycle management.
For Example:
JavaScript
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
b. Class Components
- ES6 classes that extend React.Component.
- Use this.state for state management and lifecycle methods like componentDidMount
For Example:
JavaScript
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>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;