Home > Article > Web Front-end > What about hooks, why do both vue and react choose 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!
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
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.
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.
hooks
? You didn’t understand me when you were young, just like I didn’t understand
hooks
later.
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 react@16.x
, 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 avoidclass-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
And in vue
, hooks## The definition of # may be more vague, let’s summarize:
In the(Keywords:vue
combined API, starting with
"use", a series of provided It provides methods for development capabilities such as component reuse and state management.
Combined API)
import { useSlots, useAttrs } from 'vue'; import { useRouter } from 'vue-router'; // 以上这些方法,也是 vue3 中相关的 Hook!Such as:
useSlots,
useAttrs,
useRouter etc.
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.).
hooks in
vue and
react seem to be Pretty much the same.
"use"?
hooks starts with
use. This specification also includes: Our custom
hooks.
因为(爱情 误)约定。
在 react
官方文档里,对 hooks
的定义和使用提出了 “一个假设、两个只在” 核心指导思想。(播音腔)
一个假设: 假设任何以 「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 } } }
// 组件:my-component.vue{{ name }}来写:{{ message }}很明显,
vue
组合式API里完成useState
和useMemo
相关工作的API
并没有通过useXxx
来命名,而是遵从了Vue
一脉相承而来的ref
和computed
。虽然不符合
react Hook
定义的Hook
约定,但vue
的api
不按照react
的约定好像也并没有什么不妥。参考网址:https://v3.cn.vuejs.org/api/composition-api.html
五、开始第一个自定义
hook
除了官方提供的
Hooks Api
,Hooks
的另外一个重要特质,就是可以自己进行“自定义 Hooks” 的定义,从而完成状态逻辑的复用。开源社区也都有很多不错的基于
Hooks
的封装,比如ahooks
(ahooks.js.org/zh-CN/),又比如vueuse
(vueuse.org/)我还专门写过一篇小文章介绍
vuehook
:
【一库】vueuse:我不许身为vuer,你的工具集只有lodash!。
https://juejin.cn/post/7030395303433863205
那么,我们应该怎么开始撰写 “自定义Hooks” 呢?往下看吧!
5.1 react 玩家看这里
react
官方网站就专门有一个章节讲述“自定义Hook”。(https://react.docschina.org/docs/hooks-custom.html)这里,我们扔用文章开头那个
useName
的需求为例,希望达到效果:const { name, setName } = useName(); // 随机生成一个状态属性 name,它有一个随机名作为初始值 // 并且提供了一个可随时更新该值的方法 setName如果我们要实现上面效果,我们该怎么写代码呢?
import React from 'react'; export const useName = () => { // 这个 useMemo 很关键 const randomName = React.useMemo(() => genRandomName(), []); const [ name, setName ] = React.useState(randomName) return { name, setName } }忍不住要再次感叹一次,和
mixins
相比,它不仅使用起来更棒,就连定义起来也那么简单。可能有朋友会好奇,为什么不直接这样写:
const [ name, setName ] = React.useState(genRandomName())因为这样写是不对的,每次使用该
Hook
的函数组件被渲染一次时,genRandom()
方法就会被执行一次,虽然不影响name
的值,但存在性能消耗,甚至产生其他bug
。为此,我写了一个能复现错误的demo,有兴趣的朋友可以点开验证:https://codesandbox.io/s/long-cherry-kzcbqr
2022-02-03日补充更正:经掘友提醒,可以通过 React.useState(() => randomName()) 传参来避免重复执行,这样就不需要 useMemo 了,感谢!
5.2 vue 玩家看这里
vue3
官网没有关于自定义Hook
的玩法介绍,但实践起来也并不困难。目标也定位实现一个
useName
方法:import { ref } from 'vue'; export const useName = () => { const name = ref(genRandomName()) const setName = (v) => { name.value = v } return { name, setName } }5.3
vue
和react
自定义Hook
的异同
相似点: 总体思路是一致的 都遵照着 "定义状态数据","操作状态数据","隐藏细节" 作为核心思路。
差异点:
组合式API
和React函数组件
有着本质差异vue3
的组件里,setup
是作为一个早于 “created” 的生命周期存在的,无论如何,在一个组件的渲染过程中只会进入一次。React函数组件
则完全不同,如果没有被memorized
,它们可能会被不停地触发,不停地进入并执行方法,因此需要开销的心智相比于vue
其实是更多的。本文转载自:https://juejin.cn/post/7066951709678895141
作者:春哥的梦想是摸鱼
The above is the detailed content of What about hooks, why do both vue and react choose it?. For more information, please follow other related articles on the PHP Chinese website!