current position:Home>Introduction to high order components (HOC) in react tutorial

Introduction to high order components (HOC) in react tutorial

2022-06-24 07:50:09Knowledge fatness

The purpose of this article is to give you an understanding of how high-order components work, when and why they are used . We will keep it friendly to beginners , To help you better understand this concept and why it exists . Generally speaking , Higher-order components are a functional programming method . however , This article does not require any knowledge of functional programming , But you need some React Basic knowledge of . We assume that you are already familiar with React、React Components 、React The props 、 Life cycle approach and how to use React Building basic applications .

We will introduce some functional programming concepts , These concepts will help you better understand HOC.

Let's start with a formal definition :

A higher-order component is a function that accepts a component and returns a new component .

HOC No React Or any other programming language , But from react The combination of ( Made up of components ) A pattern from which nature evolves .

Functional programming and higher-order functions

A higher-order function is a function that accepts another function as a parameter . You may have used the map function in this category .

This is a concept derived from the world of functional programming . But why in React Using the concept of functional programming in ?

The goal of this pattern is to break down the logic into simpler 、 Smaller reusable functions . The rule of thumb is that a function does only one task and does it well . This also avoids side effects ( Change anything that does not belong to this function ), And make debugging and maintenance easier .

A classic example of functional programming is multiplication :

const multiply = (x) => (y) => x * y

Similarly ,HOC Take another component as a parameter .

Let's build a HOC And learn more as we go along .

React Higher level components in HOC

Let's look directly at some code .

const rev

copyright notice
author[Knowledge fatness],Please bring the original link to reprint, thank you.

Random recommended