search
HomeWeb Front-endFront-end Q&ABriefly talk about the Hook features in Vue3 (summary sharing)

This article brings you why you should use Hook, and what is the difference between Vue 3’s Hook and React. Next, I will share it through this article. I hope it will be helpful to everyone.

Briefly talk about the Hook features in Vue3 (summary sharing)

The concept of Hook

The concept of Hook was proposed in React. First, let’s briefly introduce how Hook came about in React.

Briefly talk about the Hook features in Vue3 (summary sharing)

Briefly talk about the Hook features in Vue3 (summary sharing)

Referring to the well-known Vue 2 code structure, we see: React uses Class as a whole to encapsulate a component; a state is designed To manage variables, it is equivalent to data in Vue 2; it also has a life cycle and custom methods; the template part is written into a rendering function with the help of JSX. If you need to update the view, you must update the variables in the state through the setState method, and then the data on the view will be updated accordingly. You cannot update the data directly by updating the view.

It can be seen that unlike Vue, it is a one-way data flow. The pronunciation of Vue is "view", and "state" means state. If Vue is view-oriented, React is state-oriented.

Since React uses Class to implement components, problems arise: you must pay attention to the pointing problem of this in Class; and when components are reused and nested, the props of each layer of components must be All operations must be performed, and the logic is complicated.

So the function component was born, realizing state separation for React.

Briefly talk about the Hook features in Vue3 (summary sharing)

Here, the variable declaration, component method, and rendering function are all encapsulated into a function, and a new useEffect is added to implement the life cycle and monitor changes in state data. When this component is declared, updated, or about to be destroyed, it will call the function that defines it and output a new view.

Let’s look at how to define a component in Vue 3:

Briefly talk about the Hook features in Vue3 (summary sharing)

Is it similar to the above writing method? However, although the writing methods are similar, they are still very different in implementation. As we mentioned earlier, React is state-oriented, while Vue is view-oriented. React function components update the view by re-calling the function, integrating the life cycle into the component declaration; while Vue's setup method only replaces beforeCreate and created, other life cycles are still defined within the component, and each instance only runs setup once. Supports monitoring changes in views and data.

Some people often say that Vue is another implementation of React, but the two concepts are completely different. In fact, it can be understood that Vue adopts the design method of React while retaining its own characteristics.

So what is Hook? The definition in React is to retain the state data in the function component while integrating the life cycle function, using the entire component as a hook function.

Custom Hook

When the components are complex, some repetitive logic in multiple components can be abstracted. Before Hook was born, React and Vue both had high-order component design patterns. HOC was used in React and mixin was used in Vue 2. Why should we abandon them and use Hooks? What are the advantages of using custom Hooks? Let’s take a brief look at HOC and mixin first, and then we will know after comparing them.

Briefly talk about the Hook features in Vue3 (summary sharing)

#The principle of HOC is to pass the component as a parameter into a function, add the reuse part and use the new component as the return value, using the decorator mode. Mixins are like disassembling reused parts into small parts, and splicing them in when a certain component is needed.

In practice, mixins have the following disadvantages:

  • Introduces implicit dependencies.

  • There may be sequencing or even code conflict coverage issues between different mixins

  • mixin code will lead to snowballing complexity

  • Multiple mixins lead to unknown sources of merged items

In order to avoid these problems, React uses HOC, but it still has flaws:

  • The state of one component affects the props of many components

  • Cause hell nesting

But use a new Hook The component structure can realize flat calling of the reused parts of components, solving the problem of unknown sources of mixins and hell nesting of HOC.

Vue 3 Implementing Hook

#As mentioned earlier, React converts Class components into function components and implements Hook. In Vue 3, Hooks are implemented through the most important part of Vue 3's new features - the composite API.

Use the combined API to write components. To put it simply, the data, methods, life cycle, etc. that were previously split according to the data type are placed in a setup function, and the component only needs to call the setup function once during initialization. . The specific API will not be introduced in detail here, you can check the official documentation. (antfu explains the combined API)

Using the combined API, you can imitate React's writing method to implement a Hook. For example, this is an example of file system management:

Briefly talk about the Hook features in Vue3 (summary sharing)

Briefly talk about the Hook features in Vue3 (summary sharing)

Imagine if this code was implemented in Vue 2, it was just a The action of creating a folder requires dismantling the declared variables, methods, monitoring data, etc. into various parts. Not to mention that we also need to implement functions such as deletion, editing, copy and paste, etc. The workload of modifying the code is very huge if you think about it. .

But written in this Hook form, we can combine codes that implement the same function. Not only is the code very concise and clear, but we can also know the source of the reused components very well.

Compared with React's Hook, Vue 3 has also made some optimizations at the bottom level, lifting the restrictions of react function components and improving performance.

Summary

The general content of this article is as follows:

Briefly talk about the Hook features in Vue3 (summary sharing)

Thinking

Why is there such a concept as hook instead of the original HOC and mixin? It can be seen that a general direction of progress in program development is to become more and more abstract, similar to Since the development from a process-oriented programming language like C to an object-oriented programming language like Java, and from the development of the native front-end Three Musketeers to the use of frameworks for component development, Hook does the same thing. Encapsulate related logic together, isolate irrelevant ones, reduce coupling, expose reused logic to other components in the form of interfaces, and shield the underlying implementation.

In this way, the same function is written more concisely. Modifying a single function will not involve hidden dependencies, reducing the complexity of maintenance. The prescribed use naming makes the code easy to read and expand, and is also beneficial to multiple people. cooperation.

State is a very important concept in React. Redux used for state management is actually to make the state in React easy to manage, while Vue implements a similar Vuex, but there is no state mechanism. Similarly, both Hooks also use effect. In React, effect is also used to solve the state problem, while Vue uses it in a completely different mechanism.

React seems to have implemented a system with a state machine as the central idea, and the logic between the parts is tight. Vue uses its own method to reimplement some methods in React, making them completely separated. Which one is needed? Just assemble whichever one you want. They use two completely different concepts. It is impossible to say who is better, but when learning one framework, you can deepen your understanding by referring to the design ideas of another framework.

Some time ago, You Yuxi also answered a question on Zhihu and mentioned that from AngularJS, React to Vue, it is actually a conceptual progress. If you just imitate these ideas to make a new framework, That's just reinventing the wheel, and if we want to make a milestone progress, improving the concept is what we should do.

[Related recommendations: "vue.js Tutorial"]

The above is the detailed content of Briefly talk about the Hook features in Vue3 (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode PurposeReact Strict Mode PurposeApr 02, 2025 pm 05:51 PM

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

React Fragments UsageReact Fragments UsageApr 02, 2025 pm 05:50 PM

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use