Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to learn React Hooks principle

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to learn React Hooks principle". In daily operation, I believe many people have doubts about how to learn React Hooks principle. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to learn React Hooks principle". Next, please follow the editor to study!

Why learn the principle of React Hooks

First of all, the utilitarian point: the current front-end framework is divided into three parts: React, Vue, Angular, and React since the v16.8.0 version officially launched the concept of React Hooks, the wind has shifted sharply from the original class components to functional components, this is a design pattern, mental model level, and very recent innovation, so as long as you talk about how you can React, you will be asked in the interview about the principle of React Hooks.

Moreover, from a practical point of view, understanding the principle of React Hooks is of great benefit to our daily development and debugging; we can realize that React Hooks is not dark magic, and the strange problems we encounter in development are just caused by React Hooks and do not need to be solved by some tricky methods.

UseState / useReducer

UseState and useReducer are both about the extraction and update of state values, and there is no difference in nature. In terms of implementation, useState is a simplified version of useReducer, which uses the same set of logic.

How React Hooks saves state

It is mentioned in the official React documentation that the location where React Hooks saves the state is actually the same as that of class components. After looking through the source code, I found that this statement is true, but it is not comprehensive:

The state values of both are mounted in the memoizedState property of the component instance object FiberNode.

The data structures of the two state values are completely different; the class component directly saves the developer-defined object mounted in the state property to the memoizedState property; while React Hooks uses a linked list to save the state, and the memoizedState attribute actually stores the header pointer of the linked list.

Let's take a look at what the node of the linked list looks like-- the Hook object:

/ / react-reconciler/src/ReactFiberHooks.js export type Hook = {memoizedState: any, / / the latest state value baseState: any, / / initial state value, such as `useState (0) `, the initial value is 0 baseUpdate: Update | null, queue: UpdateQueue | null, / / temporarily save the operation on the status value More precisely, a pointer in a linked list data structure: next: Hook | null, / / points to the next linked list node}

The official document always emphasizes that React Hooks calls can only be placed at the top level of the function component / custom Hooks function body, because we can only associate with the actual saved data structure through the order of Hooks calls:

PS: although all of the above use useState and useReducer as examples, virtually all React Hooks are stored in this linked list way.

How React Hooks updates status

If you are familiar with useState API, we all know how to update your status:

Const [name, setName] = useState ('') setName ('Zhang San')

So how does the function returned by useState to update the state (hereinafter called dispatcher) work?

Instead of immediately changing the state value each time we call dispatcher (yes, the update of the state value is asynchronous), we create a modification operation-- adding a new node to the linked list mounted on the queue property of the corresponding Hook object:

The next time the function component is executed and useState is called again, React will calculate the latest status value based on the linked list of update operations mounted on each Hook. You may wonder why you want to save all the update operations, just save the latest update operation. If you think this way, you probably forgot that useState supports this syntax:

Const [name, setName] = useState ('') setName (name = > name +'a') setName (name = > name +'b') setName (name = > name +'c') / / the latest status value of name is' abc' 'when it is executed next time.

UseEffect

UseEffect is saved in a similar way to useState / useReducer and is also mounted in FiberNode.updateQueue in the form of a linked list.

Let's explain the execution principle of useEffect in terms of the lifecycle of mount and update:

Mount stage: mountEffect

According to the useEffect statements called in turn in the function body of the function component, a linked list is constructed and mounted in FiberNode.updateQueue. The data structure of the linked list node is as follows:

Const effect: Effect = {tag, / / used to identify whether the dependency has changed create, / / the user uses the function body passed in by useEffect destroy, / / the function generated after the above function body is executed to remove side effects, / / dependency list next: (null: any),}

After the component finishes rendering, traversing the linked list is executed.

Update stage: updateEffect

Similarly, when calling the useEffect statement in turn, determine whether the dependency list passed in at this time is consistent with the one stored in the linked list node Effect.deps (whether the values of the basic data types are the same; whether the references of the objects are the same), and if so, NoHookEffect on the Effect.tag tag.

Execution phase

After each component rendering is complete, it enters the execution phase of useEffect: function commitHookEffectList ():

Traversing linked list

Skip if you encounter a node where Effect.tag is marked with NoHookEffect.

If Effect.destroy is a function type, you need to execute the function that removes the side effects (as to where the Effect.destroy comes from, we'll talk about it in a minute)

Execute Effect.create and save the execution result to Effect.destroy (if the developer does not configure return, you will naturally get undefined, that is, the developer believes that there is no side effect that needs to be cleared for the current useEffect code snippet). Note that due to closures, Effect.destroy can actually access variables within the scope of this Effect.create function.

It is important to note that it is to remove the side effects of the previous round before performing this round of effect.

Other React Hooks Api

Other React Hooks Api, in fact, is similar to the principle: using linked list data structures to maintain the global state; determining whether to update the status of dependencies, and so on, which are not discussed here.

At this point, the study on "how to learn the principle of React Hooks" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report