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

What are the characteristics of hooks

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the characteristics of hooks". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the characteristics of hooks"?

1. Hooks: what is the general trend?

At the beginning of 2019, react officially had hooks capability in version 16.8.x.

In June 2019, Youyuxi put forward a proposal on vue3 Component API in vue/github-issues. (fundamentals of vue hooks)

In subsequent versions of react and vue3, the relevant hooks capabilities begin to be accepted by more people.

In addition, solid.js, preact and other frameworks also began to choose to join the hooks family.

It can be predicted that although class Component and hooks api are still neck and neck, hooks is very likely to replace class Component to become the real mainstream in the industry in the next few years.

What is hooks?

You didn't understand me when I was young, just like I didn't understand hooks later.

2.1 definition of hooks

The literal translation of "hooks" is "hook". It is not only a react, or even a special term in the front end, but a term familiar to the whole industry. Usually refers to:

When the system runs to a certain period, it will call the callback function that is registered to that time.

The more common hooks are: the hook of the windows system can listen to all kinds of events of the system, and the onload or addEventListener provided by the browser can register the methods that can be called by the browser at various times.

All of these can be called "hook".

But it is clear that the word hooks is given some special meaning in the context of a particular topic in a particular field.

Before react@16.x, when we talked about hooks, we might be talking about "the lifecycle of components."

But now, hooks has a whole new meaning.

Take react as an example, hooks is:

A series of methods that start with "use" provide the ability to completely avoid class writing and complete almost all component development work in functional components, such as life cycle, state management, logical reuse, and so on.

Simplify:

A series of methods that provide the ability to complete development work in functional components.

(remember this keyword: functional components)

Import {useState, useEffect, useCallback} from 'react';//, for example, these methods are the most typical Hooks.

In vue, the definition of hooks may be more vague, so let's sum it up:

In vue composite API, starting with "use", a series of methods provide development capabilities such as component reuse, state management, and so on.

(keywords: combined API)

Import {useSlots, useAttrs} from 'vue';import {useRouter} from' vue-router';// these methods are also related to Hook in vue3!

Such as: useSlots, useAttrs, useRouter and so on.

But subjectively, I think vue combined API itself is a key part of "vue hooks" and plays a central role in life cycle and state management in react hooks. (such as onMounted, ref, etc.).

By this standard, the definition of hooks in vue and react seems to be similar.

So why mention methods that start with "use"?

2.2 naming conventions and guidelines

Generally speaking, the naming of hooks begins with use, and this specification also includes our custom hooks.

Why?

Because (love mistake) the agreement.

In the official documentation of react, the core guiding idea of "one hypothesis, two only" is put forward for the definition and use of hooks. (broadcast cavity)

One hypothesis: suppose that any function that begins with "use" followed by an uppercase letter is a Hook.

The first one only calls Hook in the React function component, not Hook in the normal function. (Eslint determines whether a method is a React function by determining whether it is named Datuofeng.)

The second only: use Hook only at the top level, not call Hook in loops, conditions, or nested functions.

Because it is a convention, the naming of useXxx is not mandatory. You can still name your custom hook byXxx or some other way, but it is not recommended.

Because the power of convention is that we can know what it is by naming without looking at the implementation.

Why do we need hooks?

3.1 better state reuse

It's you, mixin!

In the class component mode, the reuse of state logic is a difficult thing.

Suppose you have the following requirements:

When a component instance is created, you need to create a state property: name, and randomly attach an initial value to this name property. In addition, you have to provide a setName method. You can spend and modify this state property elsewhere in the component.

More importantly, this logic should be reusable, reusing it in various business components.

Before I own Hooks, the first solution that comes to mind must be mixin.

The code is as follows: (this example is written in vue2 mixin)

/ / mix the file: name-mixin.jsexport default {data () {return {name: genRandomName () / pretend it can generate a random name}}, methods: {setName (name) {this.name = name} / / component: my-component.vue {{name}} import nameMixin from'. / name-mixin' Export default {mixins: [nameMixin], / / through mixins, you can directly obtain mounted () {setTimeout (()) = > {this.setName ('Tom')}, 3000)} defined in nameMixin.

At first glance, mixins seems to provide very good reuse capabilities, but the react official documentation directly indicates:

Why?

Because although mixins provides the ability of state reuse, it has too many disadvantages.

Drawback one: difficult to trace methods and attributes!

Just imagine, if there is this kind of code, do you doubt life:

Export default {mixins: [a, b, c, d, e, f, g], / / of course, it just means that it mixes a lot of capabilities mounted () {console.log (this.name) / / mmp! Who does this this.name come from? Do I have to blend in one by one to see the realization? }}

Or:

A.js mixins: [b.js] b.js mixins: [c.js] c.js mixins: [d.js] / / guess who this.name comes from? / / Please stop talking. My blood pressure is up.

The second drawback: coverage, the same name? What a mess your circle is!

When I tried to mix mixin-a.js and mixin-b.js to gain their capabilities at the same time, something unfortunate happened:

Because the developers of these two mixin functions sympathize with each other, they both define this.name as an attribute.

At times like this, you will deeply doubt whether mixins is a scientific way of reuse.

Drawback three: score twice? The price is high!

Again, in the above example, if my requirements change, what I need is no longer a simple state name, but a firstName and a lastName respectively.

At this point, the ability of name-mixin.js to blend in will be very embarrassing, because I can't mixins the same file twice.

Of course, there are solutions, such as:

/ dynamically generate mixinfunction genNameMixin (key, funcKey) {return {data () {return {[key]: genRandomName ()}}, methods: {[funcKey]: function (v) {this. [key] = v} export default {mixins: [genNameMixin ('firstName',' setFirstName'), genNameMixin ('lastName',' setLastName'),]}

It is true that the reuse of capabilities is completed through the dynamic generation of mixin, but this undoubtedly increases the complexity of the program and reduces readability.

Therefore, a new kind of "state logic reuse" becomes extremely urgent-- it is Hooks!

State reuse of Hook:

/ / single name const {name, setName} = useName (); / / const {name: firstName, setName: setFirstName} = useName (); const {name: secondName, setName: setSecondName} = useName ()

Compared to mixins, they are simply wonderful!

Are methods and properties easy to trace? This is great. It is clear who produced it and where it came from.

Will there be duplicate name and coverage problems? Absolutely not! The internal variable is in the closure, and the returned variable supports defining aliases.

It's been used many times, but it doesn't open N degrees? Don't you see the "three degrees of plum opening" in the code block above?

For the reason of "state logic reuse", Hooks has already made my mouth water.

3.2 Code Organization

Entropy subtraction, cosmic philosophy to coding philosophy.

Projects, modules, pages, functions, how to organize code efficiently and clearly, this seemingly simple proposition can not be fully explained even if you write a few books.

But on a page, the code of N things tangled with each other within a component was indeed a very common state before the advent of Hooks.

So what kind of improvement can Hooks writing bring to the organization of code?

(suppose each color in the figure above codes a highly relevant business logic.)

Both vue and react can be written through Hooks, aggregating related content together through "blocks of code scattered in various declaration cycles" through Hooks.

The benefits are obvious: "highly converged, improved readability". It is accompanied by "higher efficiency, less bug".

According to the theory in Physics, this kind of code organization is regarded as "entropy reduction".

3.3 easier to understand than class components

Especially this.

In react's class writing, all kinds of .bind (this) can be found everywhere. (even the official documentation has a special section describing "Why is binding necessary?" This question)

Don't laugh at vue players. This in computed: {a: () = > {this}} is also undefined.

Obviously, although binding is "necessary", it is not an "advantage", but a "fault-prone" location.

But in Hooks, you don't have to worry about this at all.

Because:

Originally there is nothing, where to cause dust.

Hooks writing directly bid farewell to this, from "function" to "function".

Mom doesn't have to worry about me forgetting to write bind anymore.

3.4 friendly gradualness

With wind it steals in night; Mute, it moistens each thing.

The meaning of progressive is: you can use it a little bit in depth.

Both vue and react only provide Hooks API and put their pros and cons there. You are not forced to use Hooks to rewrite previous class components through unacceptable break change.

You can still write class components while writing Hooks components in a project, which is painless but quietly changes everything in the evolution and development of the project.

But the trend of things is obvious, more and more people have joined the army of Hooks and combined API.

4. How to start playing hooks?

4.1 Environment and version

In the react project, the version of react needs to be higher than 16.8.0.

In vue projects, vue3.x is the best choice, but vue2.6+ with @ vue/composition-api can also start to enjoy the joy of "combined API".

4.2 Hooks writing of react

Because react Hooks only supports "functional" components, you need to create a functional component my-component.js.

/ / my-component.jsimport {useState, useEffect} from 'React'export default () = > {/ / A state attribute and an assignment method const [name, setName] = useState ('') / / side effects can be handled through useEffect useEffect (() = > {console.log (name)}) [name]) / / A name-dependent variable message const message = useMemo (() = > {return `hello, my name is ${name} `}, [name]) return {message}} can be generated through useMemo

4.3The Hooks method of vue

The Hooks writing of vue depends on the combined API, so this example uses:

{{message}} import {computed, ref} from 'vue'// defines a ref object const name = ref ('') / / defines a name.value-dependent calculation attribute const message = computed (() = > {return `hello, my name is ${name.value} `})

Obviously, the API in the vue combinatorial API that does the work related to useState and useMemo is not named by useXxx, but follows ref and computed, which are inherited from Vue.

Although it does not conform to the Hook convention defined by react Hook, there seems to be nothing wrong with vue's api not following the react convention.

5. Start the first custom hook

In addition to the official Hooks Api, another important feature of Hooks is the ability to define its own "custom Hooks" to reuse state logic.

The open source community also has many good Hooks-based wrappers, such as ahooks (ahooks.js.org/zh-CN/) and vueuse (vueuse.org/).

So, how should we start writing "custom Hooks"? Look down!

5.1 react players look here

The official website of react has a special chapter on "Custom Hook". (https://react.docschina.org/docs/hooks-custom.html)

Here, let's use the useName requirement at the beginning of the article as an example, hoping to achieve the effect:

Const {name, setName} = useName (); / / randomly generate a state attribute name that has a random name as the initial value / / and provides a method setName that can be updated at any time

If we want to achieve the above effect, how do we write the code?

Import React from 'react';export const useName = () = > {/ / this useMemo is critical const randomName = React.useMemo (() = > genRandomName (), []); const [name, setName] = React.useState (randomName) return {name, setName}}

I can't help but sigh again that compared with mixins, it is not only better to use, but also so easy to define.

Some friends may wonder why they don't just write:

Const [name, setName] = React.useState (genRandomName ())

Because this is not correct, each time a function component that uses the Hook is rendered, the genRandom () method is executed once, although it does not affect the value of the name, but there is performance consumption and even other bug.

To this end, I wrote a demo that can reproduce the error. Interested friends can click on the verification: https://codesandbox.io/s/long-cherry-kzcbqr

2022-02-03 supplement and correction: after digging friends remind, you can pass parameters through React.useState (() = > randomName ()) to avoid repeated implementation, so there is no need for useMemo, thank you!

5.2 vue players look here

There is no introduction to how to play custom Hook on vue3's official website, but it is not difficult to practice.

The target is also targeted to implement a useName method:

Import {ref} from 'vue';export const useName = () = > {const name = ref (genRandomName ()) const setName = (v) = > {name.value = v} return {name, setName}}

5.3 similarities and differences between vue and react custom Hook

Similarity: the overall idea is consistent with "defining state data", "operating state data" and "hiding details" as the core ideas.

Differences: there are essential differences between combined API and React function components

Among the components of vue3, setup exists as a life cycle earlier than "created". In any case, it only enters once in the rendering process of a component.

React function components are completely different. If they are not memorized, they may be constantly triggered, entering and executing methods, so there is actually more mental overhead than vue.

At this point, I believe you have a deeper understanding of "what are the characteristics of hooks?" you might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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