Translation: Liu Xiaoxi

Original link: dmitripavlutin.com/7-architect…

The original text is very long, but the content is so fascinating that I cannot resist translating it. This article is very helpful for writing reusable and maintainable React components. But because of the length is too long, I have divided the article, this article focuses on combination and reuse. Due to the limited level, part of the translation may not be accurate, if you have a better idea, please point it out in the comments section.

More articles can be read: github.com/YvetteLau/B…

——————————————— I am a dividing line ————————————————

combination

A composite component is a combination of smaller, specific components.

Composition is a way to create larger components by joining components together. Composition is at the heart of React.

Fortunately, the composition is easy to understand. Take a group of small pieces and combine them to create a larger one.

Let’s look at a common front-end application composition pattern. The application consists of header, bottom footer, sidebar on the left, and valid content in the middle:

<div id="root"></div>
Copy the code
function Application({ children }) {
    return (
        <div className="application box">
            <Label>Application</Label>
            {children}
        </div>
    );
}

function Header() {
    return (
        <div className="header box">
            <Label>Header</Label>
        </div>)}function Footer() {
    return (
        <div className="header box">
            <Label>Footer</Label>
        </div>)}function Sidebar({ children }) {
    return (
        <div className="sidebar box">
            <Label>Sidebar</Label>
            {children}
        </div>
    );
}

function Content({ children }) {
    return (
        <div className="content box">
            <Label>Content</Label>
            {children}
        </div>)}function Menu() {
    return( <div className="menu box"> <Label>Menu</Label> <div className="description"> <div className="text shorter" /> <div className="text" /> <div className="text shorter" /> <div className="text shorter" /> </div> </div> ); } function Article() { return ( <div className="article box"> <Label>Article</Label> <div className="description"> <div className="text shorter" /> <div className="text longer" /> <div className="text shorter" /> <div className="text" /> <div className="text shorter" /> <div className="text" /> <div className="text" /> <div className="text shorter" /> <div  className="text shorter" /> <div className="text" /> <div className="text" /> <div className="text shorter" /> <div className="text shorter" /> <div className="text longer" /> <div className="text shorter" /> <div className="longer" /> <div className="text shorter" /> <div className="text" /> <div className="text" /> <div className="text shorter" /> <div  className="text shorter" /> <div className="text" /> </div> </div> ); } function Label({ children }) { return <div className="label">&lt; {children}&gt; </div> } const app = ( <Application> <Header /> <Sidebar> <Menu /> </Sidebar> <Content> <Article /> </Content> <Footer /> </Application> ); ReactDOM.render(app, document.getElementById('root'));Copy the code

Applications demonstrate how composition builds applications. This organization organizes the code in such a way that it is expressive and easy to understand.

The React component composition is natural. The library uses a declarative paradigm that does not inhibit the expressiveness of composition.



and

.

has a

component and

has an

component.




So what does composition have to do with single responsibility and encapsulation? Let’s take a look:

The single responsibility principle describes how to break requirements into components, encapsulation describes how to organize those components, and composition describes how to glue the entire system together.

The Benefits of combination

Single responsibility

An important aspect of composition is the ability to form complex components from specific components. This divide-and-conquer approach helps complex components that are assembled to conform to SRP principles.

Reviewing the previous code snippet,

is responsible for rendering the header, footer, sidebar, and body area.

It makes sense to divide this responsibility into four sub-responsibilities, each implemented by a specialized component, namely

,

, < Content >, and

. These components are then glued to

.


Now look at the benefits of composition: make the

component consistent with the single responsibility principle in the way that the sub-components implement the single responsibility separately.

reusable

The reusable aspect of composition is that components that use composition can reuse common logic,

For example, the components

and

have some common code:

const instance1 = (
    <Composed1>/* Specific to Composed1 code... */ /* Common code... * /</Composed1>
);
const instance2 = (
    <Composed2>/* Common code... */ /* Specific to Composed2 code... * /</Composed2>
);
Copy the code

Code duplication is a bad practice (changing code in Composed1, for example, also requires changing code in Composed2), so how can components reuse common code?

First, encapsulate the Common code in a new component, such as

, and then

First, encapsulate the common code in the new component. Second,

and

should include

components in combination to avoid code duplication, as follows:


const instance1 = (
    <Composed1>
        <Piece1 />
        <Common />
    </Composed1>
);
const instance2 = (
    <Composed2>
        <Common />
        <Piece2 />
    </Composed2>
);
Copy the code

Reusable components conform to the principle of Don’t repeat yourself. This saves you time and effort, and at a later stage, helps maintain the code.

flexible

In React, a composite component controls its children by passing props to them. This brings the benefit of flexibility.

For example, a component that needs to display information based on the user’s device can be flexibly implemented using composition:

function ByDevice({ children: { mobile, other } }) { return Utils.isMobile() ? mobile : other; } <ByDevice>{{ mobile: <div>Mobile detected! </div>, other: <div>Not a mobile device</div> }}</ByDevice>Copy the code


Composite components, for Mobile devices, display: Mobile detected! ; For non-mobile devices, “Not a mobile device” is displayed.

efficient

A composable hierarchy of user interfaces. Therefore, composition of components is an efficient way to build user interfaces.

Note: The DRY principle is fine in theory, but in practice it should be avoided. It can only be used as a guide, there is no quantitative standard, otherwise every line of code in a program can only appear once, which is ridiculous, and other principles, too, serve only as a guide.

reuse

Reusable components that can be written once and used many times.

Imagine if software development was always reinventing the wheel. So when you write code, you can’t use any existing libraries or tools. You can’t even use code you’ve already written in the same application. Is it possible to write an application in a reasonable amount of time in this environment? No way.

This is a time to recognize the importance of reuse and use existing libraries or code rather than reinventing the wheel.

In-application reuse

According to the “Don’t Repeat Yourself” (DRY) principle, every piece of knowledge must have a single, unambiguous, authoritative representation in the system. This principle recommends avoiding duplication.

Code duplication adds complexity and maintenance effort, but does not add significant value. Logical updates force you to modify all duplicate code in your application.

The duplication problem can be solved with reusable components. Write once, use many times.

However, reuse is not without costs. Only one component is reusable when it meets the single responsibility principle and has a reasonable encapsulation.

Compliance with the single responsibility principle is required:

Reusing a component really means reusing its responsibilities

Components with only one responsibility are easiest to reuse.

However, when a component mistakenly has more than one responsibility, its reuse can add significant overhead. You only want to reuse one responsibility implementation, but you also get unnecessary responsibility implementation. For example, you just want a banana, but in getting a banana, you have to be forced to accept all the jungle.

Properly packaged components. The internal implementation is hidden and has explicit props so that components can be used in a variety of reuse situations.

Reuse of third-party libraries

You’ve just been given the task of adding new features to your app on a workday. Wait a few minutes before rolling up your sleeves and pounding away at the code.

The job you need to do has, in all probability, already been solved. Because React is so popular and has a great open source community, it’s wise to search to see if there are existing solutions.

Check out Brillout /awesome- react-Components, which has a list of reusable components.

Good third-party libraries have a structural impact and promote best practices. In my experience, the most influential are React-Router and Redux.

The React-Router uses declarative routing to build a one-page application. Use

to associate the URL with the component. When a user accesses a matching URL, the route renders the corresponding component.

Redux and React-Redux introduce one-way and predictable application state management. Asynchronous and impure code (such as HTTP requests) can be extracted from components to conform to the single responsibility principle and create components that are pure or almost pure.

Here is a checklist to determine if third-party libraries are worth using:

  • Documentation: Check that the library is meaningfulREADME.mdDocumentation and detailed documentation
  • Tested: A notable feature of a trusted library is its high test coverage
  • Maintenance: See how often library authors create new features, fix bugs, and perform routine maintenance

Finally, thank you for your precious time and reading this article. If this article gives you some help or inspiration, please do not spare your praise and Star. Your praise is definitely the biggest motivation for me to move forward.Github.com/YvetteLau/B…

Pay attention to the public number, join the technical exchange group