What are hooks?
In Vue3, hooks are a kind of function writing style, which essentially encapsulates certain independent functional Javascript code from a file.
The main purpose of it is that Vue3 draws from a mechanism in React, which is used to share state logic and side effects in function-based components, thereby improving code reusability.
Note: Hooks are somewhat similar to mixins in Vue2, but compared to mixins, hooks make it clearer where the reused code originates from, making it easier to understand.
Advantages of hooks
Hooks encapsulate components as independent logic. Its internal attributes, functions, etc. have a reactive effect that’s associated to external components.
The function of custom hooks is similar to the mixin technology used in Vue2, which is convenient and easy to use.
It is highly cohesive and loosely coupled, and it is reusable when encapsulated with Vue3’s combination API.
Standards that custom hooks must meet
They should have reusable functionality, only then they need to be extracted as independent hooks files.
The function name or file name should start with ‘use’, such as: useXX.
When importing, reactive variables or methods should be explicitly destructured and exposed.
Examples are as follows:
|
|
Difference between hooks and utils
Similarities: Through encapsulation with hooks and utils functions, code sharing and reuse can be achieved between components, which improves the reusability and maintainability of code.
Differences:
Different presentations: Hooks wrap things at the component level (hook functions, etc.) based on utils; utils are generally used to encapsulate logic functions, without component-related stuff.
Reactions to data: If ref, reactive, computed, these APIs in hooks are involved, the data is reactive; while utils are just plain extraction of common methods and thus are not reactive.
Different scopes of application: Hooks encapsulation can extract component status and lifecycle methods, which can be shared and reused across multiple components; utils generally refer to auxiliary functions or tool methods used to implement common operations or provide specific functionality.
Summary:
Utils are general-purpose utility functions, while hooks are a kind of encapsulation of utils, used to share state logic and side effects in components.
By using hooks, you can simplify your code and make it more readable and maintainable.
Difference between hooks and mixin
Similarities: Hooks and Mixins are both common means to extract code logic, convenient for code reuse;
Differences:
Different syntax and usage: Hooks are a way of functional programming introduced in the Composition API in Vue3, while Mixins are an object mixing mechanism in Vue2. Hooks are defined and used as functions, while Mixins are defined and applied by objects.
Different combinations and flexibility: Hooks allow developers to combine code according to logic, encapsulate it as a custom Hook function, and improve the reuse rate of code. Meanwhile, the properties and methods of Mixins in components will be merged with the properties and methods of components, and may cause naming conflicts or unpredictable behaviors.
Different reactive systems: Upgrading to Vue 3 comes with a new reactive system from Composition API that creates reactive data through reactive and ref and can more accurately control component updates and dependency tracking. Mixins use Vue 2’s reactive system, which keeps tracking and updating data more simple, but there may be some performance problems.
Different Lifecycle Hooks: Instead of lifecycle hooks in Vue 2, you can use hook functions like onMounted, onUpdated, etc. in Vue 3’s Composition API to manage the lifecycle of components more flexibly.
Advantages and disadvantages of mixins
Advantages: Code logic reuse in components;
Disadvantages:
Source of variables is unclear: The source of variables is not clear (implicitly passed in), which is not conducive to reading and makes the code hard to maintain.
Naming conflicts: The lifecycles of multiple mixins will fuse and run together, but properties and methods with the same name cannot be fused and may cause conflicts.
Overuse leads to maintenance problems: Many-to-many relationships can exist between mixins and components, and the complexity is higher (i.e., a component can reference multiple mixins, and a mixin can be referenced by multiple components).
Note: The Composition API proposed by VUE3 is aimed at solving these problems. The disadvantages of mixins are one of the main motivations behind the Composition API, which is inspired by React Hooks.
Hooks code:
Example of useCount.ts function:
|
|
useCount invoked in component:
|
|
Mixins code:
|
|
Mixins invoked in component:
|
|
These two examples display the difference in the code style and organization between using Hooks and Mixins. Hooks apply functional programming logic and states, while Mixins combine and share codes in an object-oriented way.
Vue3 custom Hooks apply at the function scope under components, while in Vue2 era, Mixins apply at a global scope under components. The global scope can sometimes be uncontrolled. Just like the var and let variable declaration keywords, const and let are corrections of var. Composition API indeed corrects the high coupling issue and the ubiquitous black box of ‘this’ in Vue2 era Option API. Vue3 custom Hooks are a step forward.
Hooks function encapsulation example
Example 1: Data Exporting (useDownload)
useDownload function encapsulation:
|
|
useDownload used in component:
|
|
Example 2: Addition and Subtraction Count (useCount)
useCount function encapsulation:
|
|
useCount function used in the component:
|
|
Example 3: Obtain Mouse Trigger Point Coordinate (useMousePosition)
useMousePosition function encapsulation:
|
|
useMousePosition used in component:
|
|
Hooks function encapsulation details are summarized
- How Hook functions receive parameters:
- Hooks function receives parameters via props, first define parameter type, then destructure internally.
|
|
- Receives parameters object, first set default values, then define parameter type.
|
|
- Destructuring rename method.
|
|
- KeyboardEvent is the type for mouse key event.
|
|
Summary
In the Vue2 era with Option API, data, methods, watch etc. are written separately, which makes the code fragmented and scattered. Once the code becomes complicated, it can easily lead to high coupling, making the code switching back and forth during maintenance cumbersome!
In the Vue3 era with Composition API, through the use of various Hooks and custom Hooks, fragmented reactive variables and methods are written in blocks according to functionality, achieving high cohesion and low coupling.