ReactJS Components – Set 2: Advanced Concepts and Real-World Examples
In the previous article, we explored the fundamentals of ReactJS components, covering functional components, class components, lifecycle methods, component composition, communication, React Fragments, Higher-Order Components (HOCs), and React Hooks. In this continuation, we will delve into more advanced concepts and provide real-world examples to showcase the power and flexibility of ReactJS components.
1. Introduction to Advanced ReactJS Components
As we advance in ReactJS development, we encounter more complex scenarios and the need for advanced techniques to solve them efficiently. In this set of components, we will explore Render Props, Context API, Error Boundaries, React Portals, and React Memoization.
2. Render Props
Render Props is an advanced pattern in React that allows components to share code and behavior by passing functions as props. It provides a way to encapsulate logic and expose it to multiple components.
```jsx
import React from 'react';
class Tab extends React.Component {
state = {
activeTab: 0,
};
selectTab = (index) => {
this.setState({ activeTab: index });
};
render() {
const { activeTab } = this.state;
const { renderTabs, renderContent } = this.props;
return (
<div>
<div>
{renderTabs(activeTab, this.selectTab)}
</div>
<div>
{renderContent(activeTab)}
</div>
</div>
);
}
}
// Usage
const TabComponent = () => {
return (
<Tab
renderTabs={(activeTab, selectTab) => (
<>
<button onClick={() => selectTab(0)} className={activeTab === 0 ? 'active' : ''}>Tab 1</button>
<button onClick={() => selectTab(1)} className={activeTab === 1 ? 'active' : ''}>Tab 2</button>
</>
)}
renderContent={(activeTab) => (
<>
{activeTab === 0 && <div>Content of Tab 1</div>}
{activeTab === 1 && <div>Content of Tab 2</div>}
</>
)}
/>
);
};
```
3. Context API
The Context API is used to manage global state in React applications, allowing data to be passed to components without manually passing props down the component tree.
3.1. Creating a Context
```jsx
import React from 'react';
const ThemeContext = React.createContext('light');
export default ThemeContext;
```
3.2. Consuming a Context
```jsx
import React from 'react';
import ThemeContext from './ThemeContext';
const ThemeToggler = () => {
return (
<ThemeContext.Consumer>
{theme => (
<button>
{theme === 'light' ? 'Switch to Dark Theme' : 'Switch to Light Theme'}
</button>
)}
</ThemeContext.Consumer>
);
};
export default ThemeToggler;
```
4. Error Boundaries
Error Boundaries are components that catch JavaScript errors during rendering, allowing developers to display fallback UI and gracefully handle errors.
```jsx
import React from 'react';
class ErrorBoundary extends React.Component {
state = {
hasError: false,
};
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error Boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong. Please try again.</h1>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<ComponentThatMightError />
</ErrorBoundary>
```
5. React Portals
React Portals provide a way to render content outside the parent component’s DOM hierarchy, making it useful for implementing overlays, modals, and tooltips.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ children }) => {
return ReactDOM.createPortal(
<div className="modal">
{children}
</div>,
document.getElementById('modal-root')
);
};
// Usage
const App = () => {
return (
<>
<h1>App Content</h1>
<Modal>
<p>This is a modal content.</p>
</Modal>
</>
);
};
```
6. React Memoization
React Memoization is a technique to optimize functional components and prevent unnecessary re-renders by caching the result of expensive computations.
```jsx
import React, { useState, useMemo } from 'react';
const ExpensiveComponent = ({ value }) => {
const expensiveResult = useMemo(() => {
// Expensive computation based on value
// For demonstration, a simple multiplication is used here
return value 2;
}, [value]);
return (
<div>
<p>Input Value: {value}</p>
<p>Expensive Result: {expensiveResult}</p>
</div>
);
};
```
7. Code Examples
Let’s explore some real-world examples of ReactJS components to demonstrate their applications and utility.
Example 1: Building a Tab Component with Render Props
```jsx
// Code for Tab component using Render Props
```
Example 2: Implementing Dark Mode with Context API
```jsx
// Code for implementing Dark Mode using Context API
```
Example 3: Error Handling with Error Boundaries
```jsx
// Code for implementing Error Boundaries
```
Example 4: Creating a Modal with React Portals
```jsx
// Code for implementing Modal with React Portals
```
Example 5: Memoizing Expensive Computations for Performance
```jsx
// Code for Memoizing Expensive Computations
```
8. Conclusion
ReactJS components empower developers to build dynamic and responsive user interfaces with ease. As we explore more advanced concepts like Render Props, Context API, Error Boundaries, React Portals, and React Memoization, we gain valuable tools to handle complex scenarios and optimize application performance. With these techniques at our disposal, we can create sophisticated and efficient React applications that deliver an exceptional user experience. Remember to experiment and apply these concepts wisely to suit your specific project requirements. Happy coding with ReactJS components!
1 thought on “ ReactJS Components – Set 2: Advanced Concepts and Real-World Examples ”