Encapsulation and reuse is a classic topic, I heard this word in the first day of writing code, but in practical production, most of the students who write code do not pay attention to the power of “encapsulation and reuse”.


Admittedly, inefficient working style is one of the main reasons why we work overtime. We may not be able to change the “leadership incompetence”, “frequent requirement changes” or even the misfortune of life, but we can do a good job of changing what we can, which is often very hard for a person.


So how do you encapsulate logic, components, and transactions in React? Let’s talk about it today.


precondition

The main purpose of encapsulation in React must be clear: get more done with less code. That’s why I advocate 250 lines and one js file below is the most reasonable approach, and I’ve found in a lot of practice that more than 250 lines of code proves that my code has a lot of room for improvement.


Some people ask me when I should be abstract, and the question is very simple: When you use copy, you immediately stop and ask the question, “Why should I copy code?” The answer is often repeated logic.


Of course, when it comes to writing programs, people are the least reliable, so I wonder if there’s a mechanism that automatically checks out how much “dumb, not-dry” code is in your project code? I invented a theory: the Internet is so developed now, the problems you encounter may have been met hundreds of years ago and solved, so you have to do just need to be able to search!


Based on this theory, I searched Github and, sure enough, found a great JS library: Danielstjules/Jsinspect, which basically detects the repetition rate in your code and prints it out, which is pretty interesting. We can write a script that detects pre-commits and generates reports of repetitive code, making code reviews easier:

Hahaha, those who have the ability can encapsulate into a comparison library


Render Props VS HOC

A lot of people say that HOC is easy to reuse with React code, but in practice, HOC doesn’t work as well as expected. Why? Let’s take a look at the most common example:


Redux and React-Redux libraries are used to send state and dispatch from Redux to Redux components. This pattern actually reuses the behavior in Redux:

  1. Wire components to Redux
  2. Inject the Redux Store into the component

Therefore, HOC is very useful as a “behavioral abstraction”. In practice, many behaviors can be abstracted into a HOC


HOC example

Many pages fetch data in ComponentDidMount, process it as it comes in, parse it, and then input it into the component. The process is:

  1. Specify a set of states to accept data returned by the back end
  2. For ComponentDidMount, fetch data, then setState, catch, etc

This is a “request-processing” behavior logic that we can expect to be very generic (because many components, many pages do this) and writing HOC makes it very easy to reuse this behavior

Transfer of data through HOC

Admittedly, this doesn’t look pretty in React, and certainly looks much better than the mixins provided by the ancient factory method.


The reason for this unsightly encapsulation is that when we only read Hello, we don’t know where Data and isLoading came from. For students who are not familiar with the project, this kind of encapsulation is confusing. The advantage is that you don’t break the internal logic and labels of the component itself.


Therefore, HOC is a very good behavior abstraction mode for enhancing component functionality without breaking the logic of the component itself. Here are a few common situations in which HOC is a good use:

  1. When a component is called externally, it is used without adding any attributes, such as the ‘
    ‘ call
  2. In cases where the logic is already written, you need to change the behavior of the component, but you don’t want to make JSX tag adjustments to the component
  3. Conditional judgment classes, such as a component that does not change any internal case, determine whether to render


Render Props example

HOC and render-props are widely used as code reuse methods in React. What are the differences between them? What is the difference between the scenes used?


In most cases, render props and hoc are interchangeable, so the main difference is:

  • Hoc is coarse-grained code reuse, meaning that it is used to reverse the behavior of an entire component without effort, with no impact on external invocation or internal use
  • Render props are fine-grained code reuse, such as when a component in a Render function relies on properties and methods


Let’s look at a simple example:

A few months ago, I wrote a drag component, Foveluy/ luy-dragger, which is very simple to use


Although we reuse our drag-and-drop behavior by writing a component (wrapping a component is actually a form of HOC), we actually find that a lot of times things can’t be reused.

  • What if I want to get the drag x, y axis of the current component?
  • What do I do if I want to get whether the current component is clicked?
  • What if I want to specify a drag area for a drag component?

Let’s write a few examples to implement one by one:


I’m tired. As a user, I just want to get a few key attributes. I have to write so much boring code and setState.


When we used renderProps to package our components, you see, our code was extremely elegant and minimal. Sure, you could write a larger HOC for the component to reuse logic like onStart XXX, but it wasn’t elegant, and in my opinion, it was stupid.


Render Props Example 2

The render props are used to encapsulate and reuse our code in a fine-grained way. This is an example of how to encapsulate and reduce code:

This code is just as stupid as the previous one


We extract XXX components such as handleShow into one component:



When used, we can easily reuse our Modal click behavior with fine granularity



Similarly, actions such as tick boxes, input box transformations, form components, and so on, can be abstracted into render props.



conclusion

  1. Use DanielstJules/Jsinspect to detect our duplicate code, which can be detected at pre-commit time. For details, see the maintainable React project structure in my previous article
  2. HOC is suitable for large-grained component reuse
  3. Render props are suitable for small-grained component reuse


Render props Awesome, with lots of packaged components for render props: Stop copying and pasting code.


jaredpalmer/awesome-react-render-propsgithub.com