Components in React
In React, components are the building blocks of any React application. They enable you to split the user interface (UI) into reusable, independent pieces. Components can be thought of as JavaScript functions or classes that return React elements describing what should appear on the screen.
Types of Components
React components can be categorized into two main types:
1. Functional Components
- Definition: Components that are JavaScript functions.
- Features:
- Simple and lightweight.
- Use React hooks (e.g.,
useState,useEffect) for managing state and side effects. - Do not require
thiskeyword. - Example :
import React, { useState } from 'react';Get Nidhi Bhanderi’s stories in your inbox
Join Medium for free to get updates from this writer.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
2. Class Components
- Definition: Components defined using ES6 classes.
- Features:
- Can maintain state using
this.stateand lifecycle methods (e.g.,componentDidMount). - Require
thisto access props and state. - Example:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
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;Why Use Components?
- Reusability: Write once, reuse across the app.
- Separation of Concerns: Encapsulate functionality and styling within components.
- Improved Readability: Simplifies complex UIs into manageable pieces.




