Skip to content

Components of reactjs

🔍 What is a React Component?

A React component is a reusable, self-contained unit that defines how a user interface (UI) appears and behaves. Components can be class-based or functional. They can also manage state and accept props (inputs from parent components).

In simple terms, React components are the building blocks of any React application. Each component controls its own logic and renders a portion of the UI.


🧩 Types of React Components

React provides two main types of components:

1️⃣ Class Components

  • Class components are the traditional way of writing components in React.
  • They extend React.Component and must have a render method to return JSX.
  • They can hold state and have lifecycle methods (e.g., componentDidMount, componentDidUpdate).

Example:

import React, { Component } from 'react';

class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

export default Welcome;

2️⃣ Functional Components

  • Functional components are simpler and easier to write. These components are typically stateless but can now have state and side-effects through React Hooks (like useState, useEffect).
  • They are just JavaScript functions that return JSX.

Example:

import React from 'react';

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

export default Welcome;

Note: With React Hooks, functional components are now capable of managing state and side effects, making them equally powerful as class components.


🎯 Key Concepts in React Components

1️⃣ Props (Properties)

  • Props are inputs passed to a component, like function arguments. They allow components to be dynamic and reusable.
  • Props are immutable – meaning a component cannot modify its own props; they are only read.

Example:

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

// Usage:
<Greeting name="Alice" />

Here, name is a prop passed to the Greeting component.


2️⃣ State

  • State is used to store dynamic data in a component. When the state changes, React automatically re-renders the component to reflect the changes.
  • State is mutable, meaning it can be changed over time.

Example (Class Component):

class Counter extends React.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>
);
}
}

Example (Functional Component with Hooks):

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
  • Here, useState hook is used in functional components to create and update state.

3️⃣ Event Handling

React allows handling events such as clicks, form submissions, and more. Event handlers are written in camelCase.

Example (Handling Button Click):

import React, { useState } from 'react';

function ClickButton() {
const [clicked, setClicked] = useState(false);

const handleClick = () => {
setClicked(!clicked);
};

return (
<div>
<button onClick={handleClick}>Click Me</button>
{clicked && <p>You clicked the button!</p>}
</div>
);
}

In this example, clicking the button triggers the handleClick function, which updates the clicked state.


4️⃣ Lifecycle Methods (Class Components)

Lifecycle methods are special methods that allow you to run code at specific points in a component’s life, such as when it mounts or updates.

Some common lifecycle methods:

  • componentDidMount(): Runs after the component has mounted.
  • componentDidUpdate(): Runs after the component updates.
  • componentWillUnmount(): Runs before the component is removed from the DOM.

Example (Class Component Lifecycle):

class MyComponent extends React.Component {
componentDidMount() {
console.log("Component mounted");
}

componentDidUpdate() {
console.log("Component updated");
}

componentWillUnmount() {
console.log("Component unmounted");
}

render() {
return <h1>Welcome to React</h1>;
}
}

5️⃣ Hooks (Functional Components)

Hooks were introduced in React 16.8 to bring state management and side-effects to functional components.

Common hooks include:

  • useState(): For managing state in functional components.
  • useEffect(): For handling side effects like data fetching, subscriptions, etc.
  • useContext(): For accessing context in functional components.

Example (Using useEffect):

import React, { useState, useEffect } from 'react';

function FetchData() {
const [data, setData] = useState(null);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array means this effect runs once, similar to componentDidMount

if (!data) return <p>Loading...</p>;

return <div>{data.name}</div>;
}

🏗️ React Component Structure

The typical structure of a React component involves:

  1. Imports: Importing dependencies, like React, Hooks, or other components.
  2. State/Props: Defining or passing state and props to manage dynamic content.
  3. Render/Return: JSX code that defines the UI structure.
  4. Event Handlers: Functions to handle user interactions (clicks, form submissions, etc.).

🧩 Composition of Components

React encourages composition over inheritance. This means that instead of inheriting features from other components, you can compose components together to build complex UIs.

  • Parent-Child Relationship: One component can contain other components. This makes the UI more modular and maintainable.

Example (Nested Components):

function Header() {
return <h1>Welcome to My App</h1>;
}

function Footer() {
return <footer>© 2025 My Company</footer>;
}

function App() {
return (
<div>
<Header />
<p>This is the main content of the app.</p>
<Footer />
</div>
);
}

Here, App is the parent component, and Header and Footer are child components.


🧑‍💻 Best Practices for React Components

  1. Keep Components Small: Each component should have a single responsibility. A component should do one thing, and do it well.
  2. Reusable Components: Break down UI elements into smaller, reusable components.
  3. Lift State Up: If two components need to share state, move the state to the closest common ancestor.
  4. Use PropTypes: Use PropTypes for type-checking props in components, making code more predictable and error-free.
  5. Avoid Side Effects in Render: Keep side effects (like data fetching) out of the render method. Use useEffect or lifecycle methods instead.

📚 Example – Counter with Two Buttons (Class and Functional)

Class Component:

class Counter extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}

increment = () => {
this.setState({ count: this.state.count + 1 });
};

decrement = () => {
this.setState({ count: this.state.count - 1 });
};

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div>
);
}
}

Functional Component:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}

🏁 Conclusion

In ReactJS:

  • Components are the building blocks that help create modular and reusable code.
  • Components can be functional or class-based, with state and props used for dynamic rendering.
  • Hooks are introduced for state and side-effects in functional components, making them as powerful as class components.
  • Component Composition allows you to build complex UIs by nesting components.