Home > Web Front-end > Vue.js > body text

What about hooks, why do both vue and react choose it?

青灯夜游
Release: 2022-03-02 10:09:19
forward
2718 people have browsed it

In this article, we will learn about hooks and talk about why both vue and react choose it, why we need hooks, and the similarities and differences between vue and react custom Hooks. I hope it will be helpful to everyone!

What about hooks, why do both vue and react choose it?

Reading this article, you will:

  • Initial understanding of Hooks in vue The current situation with react

  • Listen to the author’s definition and summary of Hooks

  • Understand "Why we need Hooks"

  • Carry out some simple Hooks practice

1. Hooks: What is the general trend?

At the beginning of 2019, react officially has hooks capabilities in the 16.8.x version.

In June 2019, You Yuxi put forward a proposal about vue3 Component API in vue/github-issues. (The basis of vue hooks)

In the subsequent react and vue3 related versions, the related hooks capabilities began to be recognized by more people accept. [Related recommendations: vuejs video tutorial]

In addition, solid.js, preact and other frameworks have also begun to choose to joinhooks Big family.

What about hooks, why do both vue and react choose it?

It is foreseeable that although class Component and hooks api are still going hand in hand, in the next few years, hooks is very likely to replace class Component and become the real mainstream in the industry.

2. What are hooks?

You didn’t understand me when you were young, just like I didn’t understand hooks later.

2.1 Definition of hooks

The literal translation of "hooks" is "hook", it is not just react, not even just the front end Rather than being a terminology specific to the industry, it is a term that is well known throughout the industry. Usually refers to:

When the system runs to a certain period, the callback function registered for that time will be called.

The more common hooks are: windows System hooks can monitor various events of the system. The onload or addEventListener provided by the browser Can register methods to be called at various times in the browser.

All of the above can be called "hook".

But obviously, under specific topics in specific fields, the word hooks is given some special meanings.

Before [email protected], when we talked about hooks, we were probably talking about the "life cycle of the component".

But now, hooks has a whole new meaning.

Taking react as an example, hooks is:

A series of hooks starting with "use" Methods, they provide you with the ability to completely avoid class-style writing and complete almost all component development work such as life cycle, state management, logic reuse, etc. in functional components.

Simplify it:

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

(Remember this keyword: Functional component)

import { useState, useEffect, useCallback } from 'react';
// 比如以上这几个方法,就是最为典型的 Hooks
Copy after login

And in vue, hooks## The definition of # may be more vague, let’s summarize:

In the

vue combined API, starting with "use", a series of provided It provides methods for development capabilities such as component reuse and state management.

(Keywords:

Combined API)

import { useSlots, useAttrs } from 'vue';
import { useRouter } from 'vue-router';
// 以上这些方法,也是 vue3 中相关的 Hook!
Copy after login

Such as:

useSlots, useAttrs, useRouter etc.

But subjectively speaking, I think

vue the combined API itself is a key part of "vue hooks", playing a role in react hooks's life cycle, The core role of state management. (Such as onMounted, ref, etc.).

What about hooks, why do both vue and react choose it?

If we look at it according to this standard, the definitions of

hooks in vue and react seem to be Pretty much the same.

So why do we mention the method that starts with

"use"?

2.2 Naming specifications and guiding ideology

Generally speaking, the naming of

hooks starts with use. This specification also includes: Our custom hooks.

Why?

因为(爱情 误)约定。

react 官方文档里,对 hooks 的定义和使用提出了 “一个假设、两个只在” 核心指导思想。(播音腔)

What about hooks, why do both vue and react choose it?

一个假设: 假设任何以 「use」 开头并紧跟着一个大写字母的函数就是一个 Hook

第一个只在: 只在 React 函数组件中调用 Hook,而不在普通函数中调用 Hook。(Eslint 通过判断一个方法是不是大坨峰命名来判断它是否是 React 函数)

第二个只在: 只在最顶层使用 Hook,而不要在循环,条件或嵌套函数中调用 Hook。

因为是约定,因而 useXxx 的命名并非强制,你依然可以将你自定义的 hook 命名为 byXxx 或其他方式,但不推荐。

因为约定的力量在于:我们不用细看实现,也能通过命名来了解一个它是什么。

以上 “一个假设、两个只在” 总结自 react 官网:

  • https://zh-hans.reactjs.org/docs/hooks-rules.html

  • https://zh-hans.reactjs.org/docs/hooks-faq.html#what-exactly-do-the-lint-rules-enforce

三、为什么我们需要 hooks ?

3.1 更好的状态复用

怼的就是你,mixin

class 组件模式下,状态逻辑的复用是一件困难的事情。

假设有如下需求:

当组件实例创建时,需要创建一个 state 属性:name,并随机给此 name 属性附一个初始值。除此之外,还得提供一个 setName 方法。你可以在组件其他地方开销和修改此状态属性。

更重要的是: 这个逻辑要可以复用,在各种业务组件里复用这个逻辑。

在拥有 Hooks 之前,我首先会想到的解决方案一定是 mixin

代码如下:(此示例采用 vue2 mixin 写法 )

// 混入文件:name-mixin.js
export default {
  data() {
    return {
      name: genRandomName() // 假装它能生成随机的名字
    }
  },
  methods: {
    setName(name) {
      this.name = name
    }
  }
}
Copy after login
// 组件:my-component.vue