The React component’s biggest benefit is reuse. However, the basic components are still not written to meet some scenarios. For example, for similar but different components, can we remove the common parts? This is where two other approaches are born: HOC and functions as child components.

High order component

HOC: Higher-order Component is not a Component. It is a design pattern based on the composition features of React. It is an advanced technique for reusing Component logic in React.

HOC is essentially a function that takes a component as an argument and returns the new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);
Copy the code

HOC wraps around the incoming component (WrappedComponent) (adds extra functionality/data), and typically doesn’t have its own UI.

How does a component obtain external resources

In the component tree, the parent component can pass data to the child components via props. If the source of the external resource is the parent of the parent component, the data has to pass through two layers of props to reach the target component, and some of the data may not be used by the non-target component, just to pass down.

In this case, we can take another approach — higher-order components, directly fetching external resources.

An 🌰

Encapsulate a time component (withTimer), which is only responsible for retrieving and updating the time logic. The format displayed on the UI is determined by the WrappedComponent.

  • withTimer.vue
import React from "react";

export default function withTimer(WrapperComponent) {
  return class extends React.Component {
    state = {
      time: new Date()};componentDidMount() {
      this.timerID = setInterval(() = > this.tick(), 1000);
    }
    componentWillUnmount() {
      clearInterval(this.timerID);
    }
    tick() {
      this.setState({
        time: new Date()}); }render() {
      return <WrapperComponent time={this.state.time} />; }}; }Copy the code
  • OneComponent.vue
import React from "react";
import withTimer from "./withTimer";

export class OneComponent extends React.Component {
  // ...
  render() {
    renturn(<div>{this.props.time.toLocaleString()}</div>); }}export default widthTimer(OneComponent);
Copy the code

Use attention

  • Do not change the original component, otherwise the original component will never look likeHOCIt was used before the enhancement
  • It’s a convention. withHOCThe display name of the wrapped component. For example, higher-order component nameswithSubscriptionAnd the display name of the wrapped component isCommentListThe display name should beWithSubscription(CommentList).
  • Don’t inrenderMethod.HOC
    render() {
    // Each call to the Render function creates a new EnhancedComponent
    // EnhancedComponent1 ! == EnhancedComponent2
    const EnhancedComponent = enhance(MyComponent);
    // This will cause subtrees to be unmounted and remounted every time they are rendered!
    return <EnhancedComponent />;
    }
    Copy the code
  • RefsThe convention for higher-order components is to pass allpropsPasses to the wrapped component, butrefIs not aprop.

Render props

Render props is a prop that external component users can use to tell components what to Render. It is a simple technique for sharing code between React components, allowing them to be more flexible without adding their own code.

How to use

Render props can be functions as child components (this.props. Children) or any other function prop, such as something prop (this.props. Something).

Children is a special built-in property of the React component. The XXX part of

XXX
is passed to the Comp component as children.

<Mouse>
{(mouse) = > (
    <p>The mouse position is {mouse.x}, {mouse.y}</p>
)}
</Mouse>

<Mouse
  something={(mouse)= > (
    <p>The mouse position is {mouse.x}, {mouse.y}</p>)} / >
Copy the code

Use with the React.PureComponent

ShouldComponentUpdate () is implemented in the React.PureComponent as a shallower way to compare prop and state. React.PureComponent improves performance.

But with Render prop, shallow comparisons always get false, so this takes away the advantage of pure.component.props.

summary

  • HOC and Render props are not new types of components, but design patterns
  • They are all aimed at reusing components in more scenarios

The resources

  • High order component: zh-hans.reactjs.org/docs/higher…
  • Render Props:zh-hans.reactjs.org/docs/render…

Introduction to the React

  • React: What were you thinking before writing components?
  • React: Talk about JSX
  • React: Full lifecycle and methods
  • React: Learn about the Virtual Dom and its policies
  • React: Two techniques for component reuse (High order components & Render Props)