Why React uses Hooks and some personal understanding

First, let's compare functional components and hooks components?

Before React16.8, there were functional components (no hooks)

Functional components:

Compared with the Hooks component, the component itself is stateless and has no side effects; it is completely controlled by the parent component. If the business is adjusted later, the functional component needs to be changed to a class component, which is very troublesome and destructive.

Hooks component:

It is stateful, so later business adjustments can also be modified on this basis.

Then talk about why you want to use Hooks , what are the defects of the previous class components?

There are two main reasons:

1. It is difficult to reuse state logic between components

  • The component is very simple at the beginning, but as the business develops, it will gradually be filled with some state logic and side effects. Each life cycle often contains some irrelevant logic. For example, componentDidMonut needs to request data, and some event monitoring needs to be set. In addition, it also contains other logic, which will cause completely unrelated code to be executed in the same method, if it is easy to generate bugs;
  • In most cases, it is not possible to split components into smaller granularities because state logic is everywhere;
  • Solution: In order to solve this problem, Hook splits the relevant parts of the component into smaller functions (such as setting subscriptions, or requesting data), rather than forcing them to be divided according to the life cycle;

2. Complex components become difficult to understand

  • For example: For example, components want to use some public state, such as redux. You may need solutions such as render props and high-level components, but such solutions change the component structure. For example, if some components use redux state management tools, it is necessary Use provider, connect high-level components to wrap, and pass the store to the target component, resulting in multi-layer nesting, increasing complexity, and causing ref blocking;
  • If you use React DevTools to observe the react application, you will eventually find that layers of packages form the final "nesting hell";

 Reference 1: React18 Hooks principle and source code analysis_哔哩哔哩_bilibili

 Reference 2:   What are the advantages and disadvantages of [react] Higher Order Components (HOC)? _Common Netizen's Blog-CSDN Blog_The disadvantages of hoc

Guess you like

Origin blog.csdn.net/u014165391/article/details/127844504