HOC vs Render Props vs Hooks

Time:2021-12-1

Warehouse address of complete high frequency question bank:https://github.com/hzfe/aweso…

Complete high frequency question bank reading address:https://febook.hzfe.org/

Related issues

  • What is hoc / render props / hooks
  • Why do you need hoc / render props / hooks
  • How to improve code reusability
  • Implementation principle of hooks
  • What are the advantages of hooks over other schemes

Answer key points

Reusability

Hoc / render props / hooks can be written in three waysImprove code reusability, but the implementation methods are different: hoc is to enhance the incoming components and return new components to the developer; Render props refers to the technology of transferring a function returned to the react component as a prop to another react component’s shared code; Hooks is a set of APIs provided by react, which enables developers to use state and other react features without writing classes.

In depth knowledge

1. Hoc (higher order component)

Hoc is the programming mode of reusing code in react. Specifically, a higher-order component is a pure function that receives a component and returns a new component. Common example: connect of react Redux connects the Redux store with the react component.

//   react-redux   connect   example
const ConnectedMyComponent = connect(mapState)(MyComponent);

``````
//   Implement a simple   HOC   example
function logProps(WrappedComponent) {
  return class extends React.Component {
    componentDidUpdate(prevProps) {
      console.log("Current props: ", this.props);
      console.log("Previous props: ", prevProps);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

2. Render Props

Render props is a programming mode for reusing code in react. It mainly solves the reuse problem of the same component logic but different rendering rules. Common example: in the react router, customize the render function and use routeprops to render business components as needed.

ReactDOM.render(
  <Router>
    <Route
      path="/home"
      render={(routeProps) => (
        <div>Customize HZFE's {routeProps.location.pathname}</div>
      )}
    />
  </Router>,
  node
);

3. React Hooks

React hooks is a set of APIs introduced by react 16.8. Developers can use state and other react functions in pure functional components with hooks without using class writing.

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

4. HOC vs Render Props vs Hooks

Pain point

In the process of rapid business iteration, components often have a lot of repetitive work and a small amount of personalized customization requirements. If the dry (don’t repeat yourself) rules are not followed, the project will be bloated and difficult to maintain. However, in many cases, components containing state logic cannot be further split. Therefore, there is a reconstruction scheme using hoc / render props before react hooks.

Advantages and disadvantages of the scheme

To assist understanding, please refer to the following pictures. The figure shows three different implementations of the drop-down list function. Compared with using a class to write all the functions of the drop-down list, these three schemes disassemble the components and improve the reusability of the code. (code source)

HOC vs Render Props vs Hooks

  • Reusability

    Hoc, render props and hooks all have the ability to improve code reusability, but the scope of application will also be different according to their design patterns: hoc enhances incoming components based on the principle of single function; Render props reuses data sources and renders UI on demand; Hooks has good universality for reuse in different scenarios.

  • Readability / ease of use

    Hoc has poor readability and ease of use.

    The method of writing hoc seems simple, but developers can’t identify the function of the method by reading the call of HOC: they can’t see the structure of receiving and returning, which increases the cost of debugging and repairing problems; When multiple HOCs are combined, the order of use cannot be determined and there is a risk of namespace conflict. It is necessary to understand the specific implementation of each hoc, which is difficult to maintain. Excessive use of hoc is not recommended, but it is more suitable for use when there is no need for personalized development and customization: it is common for third-party libraries to provide hoc type APIs for developers to enhance their functions.

    Render props is readable and easy to use.

    The code is relatively lengthy, but you can clearly see the props received by the component and the functions passed. You can rename the props attribute without naming conflict. However, it is difficult to use the data source outside the render function, and it is easy to form a nested hell.

    Hooks is readable and easy to use.

    When using hooks, you can clearly see the props received by the component and the functions passed. You can rename the props attribute without naming conflict, nesting hell, and restrictions on data source acquisition and use range. However, hooks programming should follow the practice of functional programming, otherwise the processing of dependent arrays required by hooks will cause a great mental burden.

reference material

  1. Introducing Hooks
  2. Comparison: HOCs vs Render Props vs Hooks

Recommended Today

Datawhale pandas punch in – Chapter 4 grouping

Today, I’m learning Chapter 4 – grouping, which I think is a very important and useful knowledge of pandas. This chapter mainly introduces the application of AGG, transform, apply and other functions based on the growpy function.The textbook summarizes the three operations of grouping: aggregation, transformation and filtering. 1. Polymerization: The groupby object has defined […]