Types of Components in React
Last updated 8th.Dec.2023
In the context of React, “components” refer to reusable, self-contained building blocks that encapsulate a part of a user interface (UI) and its logic. React is a JavaScript library for building user interfaces, and its component-based architecture makes it easier to manage and scale complex UIs.
About The Author
Sai Ram Soma Having 12+ years of IT experience in React JS & Native, JavaScript, Typescript. Working in a startup from day one. Accustomed to learning and keeping up with the current trend. Experience in developing feature rich web applications using React JS. Experience in developing mobile applications in Android, React Native.
What are the types of Components in React?
In the context of React, “components” refer to reusable, self-contained building blocks that encapsulate a part of a user interface (UI) and its logic. React is a JavaScript library for building user interfaces, and its component-based architecture makes it easier to manage and scale complex UIs. React components can be thought of as custom, reusable HTML elements with associated JavaScript logic. React components enable a modular and maintainable approach to building UIs, as they can be composed and reused throughout the application. The component-based structure of React promotes a clear separation of concerns and facilitates the development and maintenance of large-scale applications.
What are the Types of Components in React Js?
A fundamental element of React applications, a React Component serves as a cornerstone in the construction of React Apps. Each application crafted in React comprises components, making the process of UI development significantly more manageable. Components streamline the task of constructing user interfaces.
There are various methods for creating React Components. React primarily consists of two types of components: Functional Components and Class Components.
Yet, there are additional React components that follow patterns similar to these two types, and today we will explore them too.
Types of Componants –
- Functional Components
- Class Components
1. Functional Components
Functional components in React are a type of component that is defined as a JavaScript function. They are also known as stateless or presentational components. Historically, functional components were limited to rendering UI elements and accepting props as parameters, without having their own internal state or lifecycle methods.
However, with the introduction of React Hooks in version 16.8, functional components gained the ability to manage state and use lifecycle features, blurring the lines between functional and class components. Hooks, such as useState and useEffect, allow functional components to handle state and side effects, making them more versatile and capable.
Key characteristics of functional components include:
- Definition: They are written as JavaScript functions.
- No Internal State (historically): Functional components were initially stateless and did not have their own internal state. With Hooks, they can now manage state.
- No Lifecycle Methods (historically): Functional components do not have traditional lifecycle methods. Hooks like useEffect can be used for side effects and lifecycle behavior.
- Props Parameter: Functional components receive data and behavior from their parent component through props.
- Conciseness: Functional components are often more concise and easier to read than class components, especially for simple UI elements.
Example of a basic functional component:
function Title()
{
return <h1>I am Title</h1>;
}
Functional components are a fundamental part of modern React development, providing a concise and flexible approach to building UI elements.
2. Class Components
Class components in React are a type of component that is defined as an ES6 class. Before the introduction of React Hooks, class components were the primary way to create components with state and lifecycle methods. While functional components have gained popularity with the advent of Hooks, class components are still widely used in existing codebases.
Key characteristics of class components include:
- Definition: They are written as ES6 classes that extend the React. Component class.
- Internal State: Class components can have their own internal state, managed through the this.state object.
- Lifecycle Methods: Class components can define lifecycle methods, such as componentDidMount, componentDidUpdate, and “componentWillUnmount”, allowing developers to hook into the different phases of a component's lifecycle.
- Props: Like functional components, class components receive data and behavior from their parent component through props.
- Legacy Approach: With the introduction of Hooks, functional components have become a more modern and concise alternative to class components. However, class components are still prevalent in many existing projects.
Example of a basic class component:
class Title extends React.Component
{
render(){
return <h1>I am Title</h1>;
}
}
Class components provide a way to manage complex states and implement lifecycle methods, making them suitable for scenarios where more advanced features are required. However, as of the latest React versions, functional components with Hooks are generally recommended for new development due to their simplicity and ease of use.
Additional Components of React JS:
- Higher-Order Components
- Dumb Components
- Smart Components
- Presentational Components
- Container Components
1. Higher-Order Components
Higher-order components (HOCs) in React are an advanced pattern for reusing component logic. A HOC is a function that takes a component and returns a new component. They are akin to higher-order functions in JavaScript, which take functions as arguments or return functions. The primary purpose of an HOC is to share common functionality between components without repeating code.
Key characteristics of Higher-Order Components include:
- Function that Returns a Component: An HOC is a function that accepts a component as its argument and returns a new component.
- Reusability: HOCs allow for the reuse of common logic across multiple components, which is particularly useful for concerns like data fetching, state management, or user interface behaviors.
- Composition: HOCs can be composed together, meaning you can apply multiple HOCs to a single component to combine various behaviors.
- Props Manipulation: An HOC can modify the props of the component it wraps, add new props, or abstract state.
- Not Part of the Rendering Tree: An HOC doesn't appear as a component in the React component hierarchy. Instead, it serves as a component factory or a wrapper.
Here is an example HOC that transforms and returns usernames in uppercase:
const hoc = (MyComponent) => (props) => {
return (
<div>
<MyComponent {…props}>
{props.children.toUpperCase()}
</MyComponent>
</div>
)
}
HOCs are a powerful tool for building abstractions, sharing behaviors, and keeping your React components DRY (Don’t Repeat Yourself). However, they should be used judiciously, as overuse can lead to complexity, particularly in understanding the component’s prop flow and hierarchy.
2. Dumb Components
“Dumb components” is a term that was previously used to describe components in React that are primarily responsible for rendering UI elements and displaying data. These components are also commonly referred to as “presentational components” or “stateless components” (before the introduction of Hooks).
Key characteristics of dumb components include:
- No Internal State: Dumb components do not manage their own state. They receive data and behavior through props from their parent components.
- Focus on Presentation: Their primary responsibility is to present information and render UI elements based on the data received via props.
- No Business Logic: Dumb components avoid containing complex business logic or making decisions based on application state. They are intended to be simple and focused on the visual representation.
- Functional Components (before Hooks): Dumb components are often implemented as functional components, especially before the introduction of React Hooks. With the advent of Hooks, functional components can now have state and lifecycle methods, blurring the line between "dumb" and "smart" components.
Example of a Dumb (Presentational) Component:
import React from ‘react’;
const DumbComponent = (props) => {
return (
<div>
<p>{props.message}</p>
<button onClick={props.onClick}>Click me</button>
</div>
);
};
export default DumbComponent;
In this example, DumbComponent receives data (message) and a click handler (onClick) via props and renders a simple UI without managing any internal state.
It’s worth noting that the terminology has evolved, and the terms “dumb components” and “smart components” are less commonly used in recent React discussions. Instead, you might encounter terms like “presentational components” and “container components” or simply refer to all components as either functional or class components based on their structure and usage of state and lifecycle methods.
3. Smart Components
“Smart components” is a term that has been used in the past to describe components in React that are more involved in managing state, handling business logic, and coordinating the behavior of a part of the application. These components are also commonly referred to as “container components” or “stateful components.”
Key characteristics of smart components include:
- Internal State: Smart components can manage their own state using the state object. They handle the data and state logic for a specific part of the application.
- Business Logic: They are responsible for implementing business logic and making decisions based on the application state. This can include handling user interactions, making API calls, and managing data flow.
- Communication with Dumb Components: Smart components often communicate with "dumb components" (presentational components) by passing data and behavior as props. Dumb components focus on rendering UI elements based on the data they receive.
- Class Components (before Hooks): Smart components are often implemented as class components, especially before the introduction of React Hooks. With Hooks, functional components can now have state and lifecycle methods, blurring the line between "smart" and "dumb" components.
Example of a Smart (Container) Component:
import React, { Component } from ‘react’;
import DumbComponent from ‘./DumbComponent’;
class SmartComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleClick = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<DumbComponent message=”Click the button” onClick={this.handleClick} />
</div>
);
}
}
export default SmartComponent;
In this example, SmartComponent manages its own state (count) and handles the logic for incrementing the count. It renders a DumbComponent that presents a message and a button. The click handler for the button is provided by the smart component.
It’s important to note that as React development practices have evolved, and with the introduction of React Hooks, the terms “smart components” and “dumb components” are used less frequently. Instead, developers often refer to components based on their roles and responsibilities, such as “container components” for those that manage state and logic and “presentational components” for those focused on rendering UI.
4. Presentational Components
“Presentational components,” also known as “UI components” or “dumb components,” are components in React that are primarily responsible for rendering UI elements and presenting information. They focus on how things look and are concerned with the visual representation of the user interface. Presentational components do not manage a state or handle complex business logic; instead, they receive data and behavior through props.
Key characteristics of presentational components include:
- No Internal State: Presentational components do not manage their own state. They receive data and behavior from parent components through props.
- Focus on Presentation: Their primary responsibility is to present information and render UI elements based on the data received via props.
- Reusability: Presentational components are often designed to be reusable. They can be used in different parts of an application as long as they receive the necessary data through props.
- Functional Components (before Hooks): Presentational components are commonly implemented as functional components. Before the introduction of React Hooks, functional components were stateless and mainly responsible for presentation.
- Pure Components: Presentational components are often pure components or functional components with memoization to optimize performance. They don't rely on internal state changes for rendering.
Example of a Presentational (UI) Component:
import React from ‘react’;
const PresentationalComponent = ({ message, onClick }) => {
return (
<div>
<p>{message}</p>
<button onClick={onClick}>Click me</button>
</div>
);
};
export default PresentationalComponent;
In this example, PresentationalComponent receives data (message) and a click handler (onClick) as props. It focuses on rendering a simple UI based on the provided data and behavior.
Presentational components are an essential part of the component architecture in React. They promote reusability, readability, and maintainability by separating concerns: stateful logic is managed by container components (smart components), while presentational components handle the visual representation of the user interface.
5. Container Components
Container components, also known as “smart components” or “controller components,” are components in React that focus on managing state, handling business logic, and coordinating the behavior of a part of the application. They are responsible for data fetching, state management, and other aspects of the application’s functionality. Container components often encapsulate presentational components (dumb components) and provide them with the necessary data and behavior through props.
Key characteristics of container components include:
- Internal State: Container components can manage their own state using the state object. They handle the data and state logic for a specific part of the application.
- Business Logic: They implement business logic and make decisions based on the application state. This can include handling user interactions, making API calls, and managing data flow.
- Communication with Presentational Components: Container components communicate with presentational components by passing data and behavior as props. Presentational components focus on rendering UI elements based on the data they receive.
- Class Components (before Hooks): Container components are often implemented as class components. Before the introduction of React Hooks, class components were the primary way to manage state and lifecycle methods in React.
- Composition: Container components can be composed together, allowing developers to build complex features by combining different container components.
Example of a Container Component:
import React, { Component } from ‘react’;
import PresentationalComponent from ‘./PresentationalComponent’;
class ContainerComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
handleClick = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<PresentationalComponent message=”Click the button” onClick={this.handleClick} />
</div>
);
}
}
export default ContainerComponent;
In this example, ContainerComponent manages its own state (count) and handles the logic for incrementing the count. It renders a PresentationalComponent that presents a message and a button. The click handler for the button is provided by the container component.
Container components play a crucial role in structuring React applications, separating concerns, and promoting a modular and maintainable codebase. With the introduction of React Hooks, functional components can also serve as container components, blurring the distinction between class and functional components.
Concept of Components and their Importance in React JS
Components in software development, such as in React, embody modularity, reusability, and encapsulation. They are self-contained units that encapsulate specific functionality or UI, fostering a modular and organized code structure. Components are designed for reuse, reducing redundancy, improving maintainability, and enabling the creation of scalable applications. They promote collaboration among developers, ease debugging efforts, and contribute to a consistent user interface. In essence, components simplify development by breaking down complex systems into manageable and independent units.
Code Reusability
Importance: Components enable the creation of reusable building blocks, reducing redundancy and promoting the reuse of code. This leads to more efficient development and easier maintenance.
Maintainability
Importance: Components facilitate a modular and organized code structure, making it easier to understand, update, and debug. Changes to one component are less likely to impact others, improving overall code maintainability.
Scalability
Importance: As an application grows, the component-based architecture of React allows for scalable development. New features can be added by creating and integrating new components without disrupting existing functionality.
Collaboration
Importance: Components enhance collaboration among developers by providing clear interfaces and boundaries. Team members can work on different components independently, fostering parallel development.
Testing
Importance: Components can be tested independently, allowing for more focused and targeted testing efforts. This promotes the identification and resolution of issues early in the development process.
Consistency
Importance: Components contribute to a consistent and cohesive user interface. Design patterns can be applied consistently across different parts of an application, leading to a better user experience.
Debugging and Isolation
Importance: Components facilitate easier debugging and issue isolation. When an issue arises, developers can focus on a specific component without having to navigate through the entire codebase.
Adaptability
Importance: Components are adaptable and can be reused in various contexts. This adaptability is crucial when building complex applications with diverse requirements.
In summary, the concept of components, especially in the context of React, plays a pivotal role in simplifying development, enhancing code organization, and fostering the creation of scalable and maintainable applications. Components are a cornerstone of modern software development, promoting best practices such as modularity, reusability, and encapsulation.
Use of Components in React JS
Components are fundamental building blocks in React, serving several essential purposes:
Modularity
Components allow you to break down the user interface into small, reusable pieces. This promotes a modular and maintainable code structure.
Reusability
Once created, components can be reused throughout the application. This reduces redundancy and makes it easier to manage and update the codebase.
Abstraction
Components abstract away the complexity of the UI by encapsulating functionality and rendering logic. This abstraction makes it simpler to reason about and manage the application.
Organization
Components help in organizing the codebase by providing a clear structure. Each component can focus on a specific feature or part of the user interface.
Readability
Breaking down the UI into components enhances code readability. Developers can understand and work on smaller, self-contained units of code, making it easier to collaborate and maintain the code.
Scalability
As the application grows, using components makes it easier to scale and extend functionality. New features can be added by creating new components or by extending existing ones.
Testing
Components can be tested in isolation, simplifying the testing process. This ensures that each component behaves as expected, contributing to a more robust and reliable application.
Collaboration
Components facilitate collaboration among developers. Different team members can work on different components simultaneously, promoting parallel development.
State Management
Components can manage their own state, making it easier to handle dynamic data and user interactions. This helps in creating interactive and responsive user interfaces.
In summary, components in React contribute to code organization, reusability, maintainability, and the overall efficiency of the development process. They play a crucial role in building scalable, modular, and readable applications.
Reusable Component in React js
A reusable component in React is a modular and self-contained piece of code that encapsulates a specific piece of functionality or user interface (UI). The key characteristic of a reusable component is that it can be easily used and integrated into different parts of a React application, promoting code reusability and maintainability.
In React, components are the building blocks of the user interface, and creating reusable components is a fundamental practice. Reusable components can be used across multiple parts of an application or even across different projects, providing a consistent and efficient way to implement common functionalities.
Here are some characteristics of reusable components in React:
Modularity
Reusable components are designed to be modular, meaning they can be easily understood and used independently of other parts of the application.
Encapsulation
Components encapsulate a specific piece of functionality or UI, hiding the internal details and providing a clean interface for interaction.
Parameterization
Reusable components often accept props (properties) as input, allowing them to be customized and adapted for different use cases.
Independence
They are independent units, meaning changes to one component should not affect the functionality of other components as long as the external interface remains the same.
Ease of Integration
Reusable components are easy to integrate into different parts of the application, promoting the concept of “composition” where larger components are built by combining smaller, reusable components.
Here’s a simple example of a reusable functional component in React:
import React from ‘react’;
const ReusableComponent = ({ text }) => {
return <div>{text}</div>;
};
export default ReusableComponent;
This component can be reused in different parts of the application by passing different values for the text prop.
import React from ‘react’;
import ReusableComponent from ‘./ReusableComponent’;
const App = () => {
return (
<div>
<ReusableComponent text=”Hello, World!” />
<ReusableComponent text=”Welcome to React!” />
</div>
);
};
export default App;
In this way, the reusable component can be reused with different texts, demonstrating the reusability aspect of components in React.
FAQ’S
What are Controlled Components in React Js:
- State is managed by React.
- Input elements are controlled by the React state.
- Changes trigger a re-render based on React state.
What are Uncontrolled Components React Js:
- State is managed by the DOM.
- Input elements hold their own state.
- React is not actively involved in state management.
Key Distinctions:
- Controlled components use React to manage state for predictability.
- Uncontrolled components delegate state management to the DOM.
- Controlled components are generally preferred in React applications. Uncontrolled components may be useful in specific scenarios, such as integrating with non-React code.
A Pure Component in React is a class component that inherits from React. Pure Component. It automatically implements a should Component Update method with a shallow comparison of props and state, preventing unnecessary re-renders. Pure Components are used for performance optimization by re-rendering only when there are actual changes in data. They are beneficial for components that render frequently but have static data.
Functional components in React are JavaScript functions that serve as the building blocks for UI elements. Traditionally stateless, they receive data through props. With the introduction of Hooks, functional components can now manage state and handle side effects, making them concise, readable, and powerful for various use cases.
Web Components are a set of web platform APIs that allow for the creation of reusable and encapsulated custom elements in web documents and applications. In the context of React, web components refer to a standard for creating reusable UI components that can be used across different web frameworks.
React itself does not implement web components, but it can work with them. You can use React components as part of a web component, and vice versa. This interoperability allows developers to integrate React components seamlessly into projects that use web components or to use web components within React applications.
In short, web components in React refer to the ability to create and use components following the web components standard, enabling greater interoperability between different web technologies and frameworks.
In React, the crucial concept involves the use of props (short for properties) to transmit information to components. Given the modular nature of React, props enable the seamless sharing of data across components that require it. This aligns with React’s one-directional data flow, flowing from parent to child components.
Components offer streamlined testing by allowing each component to be tested independently, rather than across every page where it’s employed. This approach not only simplifies testing but also eases the debugging process, particularly when a component’s functionality is self-contained.