Several advanced methods for decomposing React components
React components have endless magic and great flexibility. We can play with many tricks in the design of components. But it is very important to ensure the Single responsibility principle of the component: it can make our components simpler and more convenient to maintain, and more importantly, it can make the components more reusable. This article mainly shares with you several advanced methods of decomposing React components, hoping to help you.
However, how to decompose a complex and bloated React component may not be a simple matter. This article introduces three methods of decomposing React components from the shallower to the deeper.
Method 1: Cut render() method
This is the easiest method to think of: when a component renders many elements, you need to try to separate the rendering logic of these elements. The fastest way is to split the render() method into multiple sub-render methods.
It will be more intuitive if you look at the following example:
class Panel extends React.Component { renderHeading() { // ... } renderBody() { // ... } render() { return ( <div> {this.renderHeading()} {this.renderBody()} </div> ); } }
Careful readers will quickly discover that this does not actually decompose the component itself. The Panel component still maintains its original state, props, and class methods.
How to really reduce component complexity? We need to create some subcomponents. At this time, it will definitely be a good try to adopt functional components/stateless components supported and recommended by the latest version of React:
const PanelHeader = (props) => ( // ...);const PanelBody = (props) => ( // ...);class Panel extends React.Component { render() { return ( <div> // Nice and explicit about which props are used <PanelHeader title={this.props.title}/> <PanelBody content={this.props.content}/> </div> ); } }
Compared with the previous method, this subtle improvement is revolutionary.
We created two new unit components: PanelHeader and PanelBody. This brings convenience to testing, and we can directly test different components separately. At the same time, with the help of React's new algorithm engine React Fiber, the rendering efficiency of the two unit components is optimistically expected to be significantly improved.
Method Two: Template Component
Back to the starting point of the problem, why does a component become bloated and complicated? One is that there are many and nested rendering elements, and the other is that there are many changes within the component, or there are multiple configurations.
At this point, we can transform the component into a template: the parent component is similar to a template and only focuses on various configurations.
I still need to give an example to make it clearer.
For example, we have a Comment component, which has multiple behaviors or events.
At the same time, the information displayed by the component changes according to the user's identity:
Whether the user is the author of this comment;
Whether this comment is saved correctly;
Different permissions
-
etc...
will cause different display behaviors of this component.
At this time, instead of confusing all the logic together, maybe a better approach is to use React to transfer the characteristics of React element. We transfer React element between components, so that it is more like a powerful template. :
class CommentTemplate extends React.Component { static propTypes = { // Declare slots as type node metadata: PropTypes.node, actions: PropTypes.node, }; render() { return ( <div> <CommentHeading> <Avatar user={...}/> // Slot for metadata <span>{this.props.metadata}</span> </CommentHeading> <CommentBody/> <CommentFooter> <Timestamp time={...}/> // Slot for actions <span>{this.props.actions}</span> </CommentFooter> </div> ... ) } }
At this point, our real Comment component is organized as:
class Comment extends React.Component { render() { const metadata = this.props.publishTime ? <PublishTime time={this.props.publishTime} /> : <span>Saving...</span>; const actions = []; if (this.props.isSignedIn) { actions.push(<LikeAction />); actions.push(<ReplyAction />); } if (this.props.isAuthor) { actions.push(<DeleteAction />); } return <CommentTemplate metadata={metadata} actions={actions} />; } }
metadata and actions are actually the React elements that need to be rendered under specific circumstances.
For example:
If this.props.publishTime exists, metadata is
; The opposite is Saving....
If the user has logged in, it needs to be rendered (that is, the actions value is)
and ; If it is the author himself, the content that needs to be rendered must be added with
.
Method Three: High-Order Components
In actual development, components are often contaminated by other requirements.
Imagine a scenario like this: We want to count the click information of all links on the page. When the link is clicked, a statistics request is sent, and this request needs to contain the id value of the document of this page.
A common approach is to add code logic to the life cycle functions componentDidMount and componentWillUnmount of the Document component:
class Document extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { // Naive check for <a> elements if (e.target.tagName === 'A') { sendAnalytics('link clicked', { // Specific information to be sent documentId: this.props.documentId }); } }; render() { // ... } }
Several problems with doing this are:
Related component Document In addition to its main logic: displaying the main page, it has other statistical logic;
If there is other logic in the life cycle function of the Document component, then this Components will become more ambiguous and unreasonable;
statistical logic code cannot be reused;
Component reconstruction and maintenance will become more complicated difficulty.
In order to solve this problem, we proposed the concept of higher-order components: higher-order components (HOCs). Without explaining this term obscurely, let’s look directly at how to reconstruct the above code using higher-order components:
function withLinkAnalytics(mapPropsToData, WrappedComponent) { class LinkAnalyticsWrapper extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { // Naive check for <a> elements if (e.target.tagName === 'A') { const data = mapPropsToData ? mapPropsToData(this.props) : {}; sendAnalytics('link clicked', data); } }; render() { // Simply render the WrappedComponent with all props return <WrappedComponent {...this.props} />; } } ... }
It should be noted that the withLinkAnalytics function does not change the WrappedComponent component itself, let alone Will change the behavior of the WrappedComponent component. Instead, a new wrapped component is returned. The actual usage is:
class Document extends React.Component { render() { // ... } } export default withLinkAnalytics((props) => ({ documentId: props.documentId }), Document);
In this way, the Document component still only needs to care about the parts it should care about, and withLinkAnalytics gives the ability to reuse statistical logic.
The existence of high-order components perfectly demonstrates React’s innate compositional capabilities. In the React community, react-redux, styled-components, react-intl, etc. have generally adopted this approach. It is worth mentioning that the recompose class library makes use of high-order components and carries them forward to achieve "brain-expanding" things.
The rise of React and its surrounding communities has made functional programming popular and sought after. I think the ideas about decomposing and composing are worth learning. At the same time, a suggestion for development and design is that under normal circumstances, do not hesitate to split your components into smaller and simpler components, because this can lead to robustness and reuse.
Related recommendations:
React component life cycle instance analysis
The most complete method to build React components
Detailed explanation of how store optimizes React components
The above is the detailed content of Several advanced methods for decomposing React components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and
