What are Components and Types of Components in React JS
Understanding React Components:
React component is a reusable piece of code responsible for rendering a part of the user interface. These components can be as simple as a button or as complex as an entire form. The modular nature of React components allows developers to break down their applications into manageable and reusable chunks, fostering a clean and organized codebase.
Example:
// Functional Component
const Greeting = () => {
return <h1>Hello, React!</h1>;
};In this example, Greeting is a functional component that simply renders an <h1> element with the greeting message. Functional components are concise and efficient for presentational purposes.
Types of React Components:
1. Functional Components: The Essence of Simplicity
Functional components are the bedrock of React simplicity. They are stateless, focusing on presenting UI elements without managing state or lifecycle methods. These components are ideal for scenarios where complexity is unnecessary.
Example:
// Functional Component with Props
const WelcomeMessage = (props) => {
return <p>Welcome, {props.name}!</p>;
};Here, WelcomeMessage is a functional component that receives a name prop and displays a personalized welcome message.
2. Class Components: Power and Dynamics
Class components, on the other hand, introduce power and dynamics to React applications. They can manage state and incorporate lifecycle methods, making them suitable for components requiring dynamic behavior and interaction.
Example:
// Class Component with State
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}In this example, Counter is a class component that manages a count state and renders a button to increment the count.
3. Higher-Order Components (HOCs): Reusable Logic
Higher-Order Components (HOCs) are functions that take a component and return a new enhanced component. They enable the sharing of component logic across different parts of an application, promoting code reuse and maintaining a clean codebase.
Example:
// Higher-Order Component
const withLogger = (WrappedComponent) => {
return class WithLogger extends React.Component {
componentDidMount() {
console.log('Component is mounted!');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
// Using the HOC
const EnhancedComponent = withLogger(Counter);Here, withLogger is a higher-order component that logs when the wrapped component is mounted. The EnhancedComponent is the result of applying this HOC to the Counter component.
4. Pure Components: Rendering Efficiency
React introduces pure components, which automatically implement shouldComponentUpdate with a shallow prop and state comparison. This optimization reduces unnecessary renders, enhancing the rendering efficiency of the application.
Get React Masters’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
// Pure Component
import React, { PureComponent } from 'react';
class MemoizedComponent extends PureComponent {
render() {
return <p>Memoized Component</p>;
}
}MemoizedComponent is a pure component that ensures efficient rendering by comparing props and state changes before deciding to render.
5. Stateless Functional Components:
While functional components are generally stateless, React introduced a syntax that explicitly designates a component as stateless functional. This syntax is concise, emphasizing a straightforward approach to rendering UI elements without the complexities of state or lifecycle methods.
Example:
// Stateless Functional Component
const Header = () => <h1>Welcome to React World!</h1>;In this example, Header is a stateless functional component that renders a welcoming message.
6. Stateless Class Components:
Stateless class components are an interesting hybrid, providing the simplicity of functional components while allowing the use of lifecycle methods. Although somewhat unconventional, this type of component can be useful in specific scenarios.
Example:
// Stateless Class Component
import React, { Component } from 'react';
class Message extends Component {
render() {
return <p>{this.props.message}</p>;
}
}Here, Message is a stateless class component that receives a message prop and renders it.
7. Context API Components:
React’s Context API allows the creation of components that can access the global state without the need for prop drilling. Context components enable the sharing of data across the component tree, streamlining state management.
Example:
// Context Provider Component
import React, { createContext, useState } from 'react';
export const UserContext = createContext();
const UserProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};In this example, UserProvider is a context provider component that manages the user state. Consumer components can then access this context to consume the user data.
8. Suspense Components:
With the introduction of React Suspense, components can now handle asynchronous operations more gracefully. Suspense components allow for smoother handling of data fetching and code splitting, enhancing the user experience.
Example:
// Suspense Component
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
const App = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);Here, App is a suspense component that dynamically loads LazyComponent with a loading fallback.
Conclusion:
In conclusion, React components are the architects of dynamic and interactive user interfaces. From the simplicity of functional components to the power dynamics of class components and the reusability of higher-order components, each type plays a crucial role in shaping the React ecosystem. Embrace the modularity, leverage the strengths of diverse components, and embark on a journey of creating robust and scalable React applications.








