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 realize hooks with react

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

Share

Shulou(Shulou.com)05/31 Report--

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

React's hooks is a feature that appears after fiber, so many people mistakenly think that hooks has to rely on fiber to achieve, in fact, it is not, the two are not necessarily related.

Now, hooks is implemented not only in react, but also in frameworks such as preact, react ssr, midway, and so on, which are independent of fiber.

Let's take a look at how hooks is implemented in these different frameworks:

How to implement hooks with react

React describes the interface through jsx, which is compiled into render function by compilation tools such as babel or tsc, and then executes to generate vdom:

The render function here is React.createElement before React17:

After React 17, it was replaced by jsx:

This jsx-runtime will be introduced automatically, so you don't have to keep a React import for each component as before.

Render function execution generates vdom:

The structure of vdom is as follows:

Before React16, the vdom will be rendered recursively to add, delete and modify the real dom.

After React16 introduced the fiber architecture, it took one more step: first convert vdom to fiber, and then render fiber.

The process of converting vdom to fiber is called reconcile, and the final process of adding, deleting and modifying the real dom is called commit.

Why do you want to make such a conversion?

Because vdom has only references to the child node children, there are no references to the parent node parent and other sibling nodes sibling, which results in a recursive rendering of all vdom nodes to dom at once, which is uninterruptible.

What happens if I interrupt? Because the parent and sibling nodes are not recorded, you can only continue to work on the child nodes, but not the rest of the vdom.

That's why React introduces this fiber structure, that is, references such as parent node return, child node child, sibling node sibling, etc., which can be broken, because all the nodes that have not been processed can be found after being broken and then restored.

The structure of the fiber node is as follows:

This process can be interrupted, and naturally can be scheduled, that is, the process of schdule.

So the fiber architecture is divided into three stages: schdule, reconcile (vdom to fiber) and commit (update to dom).

Hooks can be used within a function component to access values that are stored on the fiber node.

For example, six hook are used in this function component:

Then there is a 6-element memorizedState linked list on the corresponding fiber node:

Concatenated by next:

Different hook accesses values on different elements of the memorizedState linked list, which is how react hooks works.

This linked list has a creation phase and an update phase, so you will find that the final implementation of useXxx is divided into mountXxx and updateXxx:

The mount phase here creates the hook node and assembles it into a linked list:

The created hook linked list is hung on the memorizedState attribute of the fiber node.

Then when you update, you can naturally retrieve the hook linked list from the fiber node:

In this way, in multiple renderings, the api of useXxx can find the corresponding memorizedState on the fiber node.

This is how react hooks works, and you can see that it stores hook on the fiber node.

So what's the difference between preact?

How to implement hooks with preact

Preact is a more lightweight framework compatible with react code, supporting class components and function components, as well as react features such as hooks. However, it does not implement the fiber architecture.

Because it mainly considers the extreme of volume (only 3kb), not the extreme of performance.

We just learned that react stores the hook linked list on the fiber node, so where does the preact store the hook linked list without a fiber node?

In fact, it is easy to think that fiber has only modified vdom to improve performance, which is not essentially different from vdom, so why don't you just store hook on vdom?

Indeed, preact puts the hook linked list on vdom.

For example, this function component has four hooks:

Its implementation is to access the corresponding hook on vdom:

Instead of dividing hook into mount and update phases as react does, it merges them together.

As shown in the figure, it stores hooks on an array of component.__hooks and accesses it through subscript.

This component is an attribute on vdom:

That is, the value of hooks is stored on the array of vnode._component._hooks.

Compare the differences between react and preact in implementing hooks:

In react, the hook linked list is stored on the fiberNode.memorizedState attribute, and in preact, the hook linked list is stored on the vnode._component._hooks attribute.

The hook linked list in react is concatenated through next, and the hook linked list in preact is an array, accessed by subscript.

React separates the creation and update of hook linked lists, that is, useXxx is divided into mountXxx and updateXxx, while preact is combined and processed together.

Therefore, the implementation of hooks does not rely on fiber, it is just to find a place to store the hook data corresponding to the component, and it doesn't matter where you can get it when rendering.

Because vdom and fiber are strongly related to component rendering, they are stored on these structures.

For example, when react ssr implements hooks, it does not exist on either fiber or vdom:

How to implement hooks with react ssr

In fact, react-dom package can do not only csr, but also ssr:

Use the render method of react-dom when csr:

Use react-dom/server 's renderToString method or renderToStream method when ssr:

Do you think ssr will do the conversion from vdom to fiber?

Definitely not. Fiber is a structure introduced to improve the rendering performance when running in the browser, to make the calculation interruptible and to do the calculation in the idle time.

Server rendering naturally does not require fiber.

Where does it store the hook linked list if it doesn't need fiber? Vdom?

It can be put on vdom, but it doesn't.

For example, the hooks of useRef:

It is a linked list concatenated with next starting from firstWorkInProgressHook.

FirstWorkInProgressHook originally created the first hook node with createHook:

It is not mounted on vdom.

Why?

Because ssr only needs to be rendered once and does not need to be updated, there is no need to hang it on vdom.

Just clear the hook linked list each time you finish processing the hooks for each component:

So, when react ssr, hooks exists on the global variable.

Compare the principles of hooks implementation between react csr and ssr:

Fiber is created from vdom in csr to make rendering interruptible and improve performance through idle scheduling, but not in ssr, which is directly rendered by vdom

When csr, the hooks is saved to the fiber node, while the ssr is directly placed on the global variable, and each component is emptied after processing. Because I won't use it again.

Csr divides the creation and update of hook into two phases: mount and update, while ssr only deals with it once and only has the creation phase.

The implementation principle of hooks is not complicated, which is to store a linked list in a context, and then hooks api accesses the corresponding data from different elements of the linked list to complete their respective logic. This context can be vdom, fiber, or even a global variable.

However, the idea of hooks is quite popular. Midway, the server-side framework of Taobao, has introduced the idea of hooks:

How to implement hooks with midway

Midway is a Node.js framework:

The server-side framework naturally does not have the structure of vdom and fiber, but the idea of hooks does not depend on these. To implement api of hooks, you only need to put a linked list in a context.

Midway implements an api similar to react hooks:

I haven't seen exactly where the hook linked list exists, but we have mastered the implementation principle of hooks, as long as there is a context to store the hook linked list, anywhere.

At this point, the study on "how to achieve hooks in react" 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