3.4 C
New York
Thursday, February 2, 2023

How To Reuse React Components | by Sabesan Sathananthan | Codezillas


Mixins, HOC, render props, and Hooks are four ways to reuse components

Now frontend engineering is more and more important. Although Ctrl+C and Ctrl+V can also be used to complete requirements, once they are modified, it becomes a huge task. Therefore, copying of code is reduced, and the packaging and reuse capabilities are increased to achieve maintainability and reversibility. The code used becomes particularly important.

In React, components are the main unit of code reuse. The combination-based component reuse mechanism is quite elegant, but for more fine-grained logic (state logic, behavior logic, etc.), reuse is not so easy. It is difficult to disassemble the state logic as a reusable function or component. In fact, before the appearance of Hooks, there was a lack of a simple and direct way of component behavior extension, which is considered to be mixins, higher-order components (HOC), and render props. The upper-level model explored under the existing (component mechanism) game rules has not solved the problem of logic reuse between components from the root. This is my 38th Medium article.

Of course, React no longer recommends using mixins as a reuse solution for a long time, but it can still provide support for mixins through create-react-class. Note that mixins are not supported when declaring components in ES6 classes.

Mixins allow multiple React components to share code. They are very similar to mixins in Python or traits in PHP. The emergence of the mixin solution comes from an OOP intuition. In the early days, it only provided React.createClass() API to define components. (In React v15.5.0, it is officially abandoned and moved to create-react-class). Naturally, (class) inheritance has become an intuitive attempt, and in JavaScript prototype-based extension mode, it is similar to the inherited mixin scheme. It has become a good solution. Mixin is mainly used to solve the reuse problem of life cycle logic and state logic, and allows the component life cycle to be extended from the outside. This is especially important in Flux and other modes, but many defects have also appeared in continuous practice:

  • There is an implicit dependency between the component and the mixin (Mixin often depends on the specific method of the component, but the dependency is not known when the component is defined).
  • There may be conflicts between multiple mixin (such as defining the same state field).
  • Mixin tends to add more states, which reduces the predictability of the application and leads to a sharp increase in complexity.
  • Implicit dependencies lead to opaque dependencies, and maintenance costs and understanding costs are rising rapidly.
  • It is difficult to quickly understand the behavior of components, and it is necessary to fully understand all the extension behaviors that rely on mixin and their mutual influence.
  • The method and state field of the component itself is afraid to be easily deleted because it is difficult to determine whether mixin depends on it.
  • Mixin is also difficult to maintain, because Mixin logic will eventually be flattened and merged together, and it is difficult to figure out the input and output of a Mixin.

There is no doubt that these problems are fatal, so Reactv0.13.0 abandoned Mixin static crosscutting (similar to inherited reuse) and moved to HOC higher-order components (similar to combined reuse).

Example

The example of the ancient version, a common scenario is: A component needs to be updated regularly. It is easy to do it with setInterval(), but it is very important to cancel the timer when it is not needed to save memory. React provides a lifecycle method to inform the component. The time of creation or destruction, the following Mixin, use setInterval() and ensure that the timer is cleaned up when the component is destroyed.

After Mixin, HOC high-order components take on the heavy responsibility and become the recommended solution for logical reuse between components. High-order components reveal a high-order atmosphere from their names. In fact, this concept should be derived from high-order functions of JavaScript. The high-order function is a function that accepts a function as input or output. It can be thought that currying is a higher-order function. The definition of higher-order components is also given in the React document. Higher-order components receive components and return new components. function. The specific meaning is: High-order components can be seen as an implementation of React decoration pattern. High-order components are a function, and the function accepts a component as a parameter and returns a new component. It will return an enhanced React components. High-order components can make our code more reusable, logical and abstract, can hijack the render method, and can also control propsand state.

Comparing Mixin and HOC, Mixin is a mixed-in mode. In actual use, Mixin is still very powerful, allowing us to share the same method in multiple components, but it will also continue to add new methods and attributes to the components. The component itself can not only perceive but also need to do related processing (such as naming conflicts, state maintenance, etc.). Once the mixed modules increase, the entire component becomes difficult to maintain. Mixin may introduce invisible attributes, such as in the Mixin method used in the rendering component brings invisible property props and states to the component. Mixin may depend on each other and is coupled with each other, which is not conducive to code maintenance. In addition, the methods in different Mixin may conflict with each other. Previously React officially recommended using Mixin to solve problems related to cross-cutting concerns, but because using Mixin may cause more trouble, the official recommendation is now to use HOC. High-order component HOC belong to the idea of ​​ functional programming. The wrapped components will not be aware of the existence of high-order components, and the components returned by high-order components will have a functional enhancement effect on the original components. Based on this, React officially recommends the use of high-order components.

Although HOC does not have so many fatal problems, it also has some minor flaws:

  • Scalability restriction: HOC cannot completely replace Mixin. In some scenarios, Mixin can but HOC cannot. For example, PureRenderMixin, because HOC cannot access the State of subcomponents from the outside, and at the same time filter out unnecessary updates through shouldComponentUpdate. Therefore, React After supporting ES6Class, React.PureComponent is provided to solve this problem.
  • Ref transfer problem: Ref is cut off. The transfer problem of Ref is quite annoying under the layers of packaging. The function Ref can alleviate part of it (allowing HOC to learn about node creation and destruction), so the React.forwardRef API API was introduced later.
  • WrapperHell: HOC is flooded, and WrapperHell appears (there is no problem that cannot be solved by one layer, if there is, then two layers). Multi-layer abstraction also increases complexity and cost of understanding. This is the most critical defect. In HOC mode There is no good solution.

Example

Specifically, a high-order component is a function whose parameter is a component and the return value is a new component. A component converts props into a UI but a high-order component converts a component into another component. HOC is very common in React third-party libraries, such as Redux’s connect and Relay’s createFragmentContainer.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles