Sitemap

Components in React

1 min readDec 28, 2024

--

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 this keyword.
  • Example :

Get Nidhi Bhanderi’s stories in your inbox

Join Medium for free to get updates from this writer.

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;

2. Class Components

  • Definition: Components defined using ES6 classes.
  • Features:
  • Can maintain state using this.state and lifecycle methods (e.g., componentDidMount).
  • Require this to 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.

--

--