I have also been in Nanjing Baiyun for three years, from an ignorant college student to an increasingly mature young man. During these three years, I have also done a lot of projects, including React and VUE technology stack. Here, I would like to talk about my views on these two mainstream frameworks. React and The Vue camp have been at each other’s throats, but now it seems vue colleague Yibao is dismissive: “Huh? , the react?” React colleague Yiyang: “Huh? Vue?” (I laugh at the thought of it)

1. Panorama

A screenshot from the kaikaiba online class of Dasheng teacher

Second, the background

React: professional

  • React was created in 2011 (FaxJS),
  • July 3, 2013 v0.3.0
  • March 30, 2016 v0.14.8
  • April 9, 2016 v15.0.0
  • On September 27, 2017, V16.0.0, Fiber was officially born
  • React 16.8 is officially supported by hooks syntax.
  • V17, 22 October 2020

To solve the problem

React is used to solve problems. We build React to solve one problem:building large applications with data that changes over time.

Legends of the vue:

It started as a personal project in 2013, but now it has become one of the top three front-end frameworks in the world, and is the preferred front-end framework in Mainland China. Interviewer: Why did you learn to use VUE? Answer: because patriotic!)

  • In 2013,In theGoogleWork for you in Rain Creek, byAngularInspired by, extracted his favorite parts from it, developed a lightweight framework, originally namedSeed.
  • In the same year in DecemberThe seed germinated and was renamedVueVue is French for View), version 0.6.0.
  • 2014.01.24.VueThis release is official, version 0.8.0.
  • Released in2014.02.250.9.0 has its own codename:AnimatrixThe name comes from the animated version of The Matrix, and since then, major releases have had their own code names.
  • 0.12.0 published on2015.06.13The codeDragon Ball(Dragon Ball), this year,VueThere was an explosion,LaravelCommunity (a popularPHPCommunity of frameworks) for the first time Vue.VueinJSThe community is also known.
  • 1.0.0 Evangelion(New Age Evangelion) YesVueThe first milestone in history. In the same year,vue-router(2015-08-18),vuex(2015-11-28),vue-cli(2015-12-27) has been released in succession, markingVueEvolving from a view-layer library to an incremental framework. A lot of front end students have also become from this versionVueThe user (vue1Pure and pure response).
  • October 1, 2016 2.0.0 Ghost in the Shell[Ghost in the Shell] was the second major milestone that it absorbedReacttheVirtual DomSolution, also supports server-side rendering.
  • February 4, 2019For a long time before the 2.6 release, the Vue core team was busy working on VUE-CLI3.0, gathering requirements and releasing itvue2Penultimate release (2020 release)
  • September 18, 2020With theA framework that anyone can learn quickly and access easilyThe mission ofvue3Here it came, along with the New Age Packing tool that same yearvite(The future may replacewebpack)

Vue mass foundation diagram is as follows:

Third, technical thought

React is a functional concept. Components use JSX syntax, all in JS, and HTML and CSS are integrated into javaScript. JSX syntax is relatively flexible.

The whole idea of VUE is still to embrace the classic HTML (structure)+ CSS (presentation)+ JS (behavior) format. Vue encourages developers to use templates and provides directives for developers to use such as V-if, V-show, V-for, etc. As a result, developing a VUE application feels like writing a classic Web application (structure, presentation, behavior separation).

Some of the usual data management (props, data vs State), component writing, lifecycle similarities and differences are not to be compared here.

1. Take the similarities and differences of keys for example

React and Vue have the same ultimate purpose in adding keys to lists: obtain the corresponding VNodes in OLdvNodes more accurately and faster, and improve performance. But there are some differences in the algorithms they implement.

react

React uses the loop index as the key for the first render if the subcomponent does not provide a key. Source code is essentially violence comparison method: because single linked list Fiber can not use double pointer algorithm, so can not use double pointer optimization algorithm. There are two rounds of traversal in general, the first round of traversal: processing the updated nodes. Second traversal: Process the remaining nodes that are not part of the update.

To reduce algorithm complexity, the React diff defaults to:

  1. Apply only to sibling elementsDiff. If aDOMThe node crosses the hierarchy in two successive updates, thenReactNo attempt will be made to reuse him.
  2. Two different types of elements produce different trees. If the element is controlled bydivintop.ReactWill be destroyeddivAnd its descendant nodes, and create p and its descendant nodes.
  3. To determinekeyTo determinetype, the same node if the two are the same. Update > Add/Remove
vue

Vue performs better than React in diff performance than React in diFF performance. When I read the source code and the book, I was impressed. The final output result is [0, 2,3], indicating that the index of the strongest growth sequence is 0,2,3 respectively. The corresponding values are 2,6,8. In other words, the longest continuous increment in this array is the 2,6, and 8 elements of the array.

So what is the purpose of using this method after all this effort in vue3? In the process of DOM-DIff, Vue2 preferentially deals with the situations of special scenes, namely head to head, head to tail, tail to head and so on.

In the process of DOM-DIff, Vue3 finds the longest stable sequence according to the newIndexToOldIndexMap index list of the new and old nodes. Through the algorithm comparison of the longest growing sub-sequence, it finds the nodes that do not need to be moved between the old and new nodes and reuses them in place. Operation is performed only on nodes that need to be moved or have patch(new and deleted nodes, etc.) to maximize replacement efficiency, which is a qualitative improvement compared with Vue2.

2. Macro comparison of DIff

react

In React, if the state of a component changes, React will re-render the component and all its descendants. However, re-rendering does not mean discarding the last render result completely. React will still use diff to compare the virtual DOM twice and patch it to the real DOM. However, if the component tree is too large, diff can actually have some overhead. React internally optimizes the diff algorithm with Fiber, and externally advises developers to use shouldComponentUpdate pureComponent to circumvent the problem.

vue

Vue2 responds to object.defineProperty and overwrites getters and other operations to implement observer mode. Once data changes, it does not compare the entire component tree like React, but updates component instances where the data state changes.

3. Life cycle

React lifecycle

old 15.x-16

Trigger phase React Core lifecycle
Mount the stage Constructor, componentWillMount, render, componentDidMount,
The update process ComponentWillReceiveProps, shouldComponentUpdate, render, componentDidUpdate
Unloading phase componentWillUnMount

new 16+

Trigger phase React Core lifecycle
Mount the stage Constructor,getDerivedStateFormProps, render, componentDidMount
The update process getDerivedStateFormProps,getSnapshotBeforeUpdateShouldComponentUpdate, render, componentDidUpdate
Unloading phase componentWillUnMount

Other: componentDidCatch

The React lifecycle naming has always been very semantic (whisper BB: It’s stinky, long and hard to remember)

Vue life cycle
Option type API Hook inside setup
beforeCreate
created
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount(vue2 beforeDestory) onBeforeUnmount
unmounted(vue2 destoryed) onUnmounted
errorCaptured onErrorCaptured
renderTracked(Vue3 state tracking) onRenderTracked
renderTriggered(VuE3 state trigger) onRenderTriggered
activated onActivated
deactivated onDeactivated

4. Functional programming

Both sides have made massive changes, and although the source code is different, the design and simplicity of the code are definitely improving.

react hooks

The original cumbersome life cycle of compomentDidUpdate = useEffect is not exactly the same, but in most scenarios, from the developer level, we are more concerned about the effects of data changes in props or state. Saves the developer the process of comparing before and after values. React (Vue Watch)

Vue3 composite API

The vue3 composite API borrows some of the ideas from the React hooks, which, it has to be said, are better than the React hooks, and the framework has made a lot of optimizations of its own.

react vue
UseState, ref Reactive, ref
useEffect OnMounted, watch, watchEffect, onUnmounted
The similar parts are sorted out above. UseEffect and watchEffect are compared
function() {
    useEffect(() = >{
        // Triggered when demo changes
        console.log(demo)
    },[demo])
    
    return (
        <div>react</div>)}Copy the code
import {reactive, watchEffect} from 'vue'
export default {
    setup() { 
          const state = reactive({ count: 0.name: 'zs' })
          watchEffect(() = > {
            console.log(state.count)
            console.log(state.name)
          })
          return {
            state
          }
    }
}
Copy the code

The new APIwatchEffect doesn’t even need to listen for changes to trigger side effects due to the responsive mechanism within the source code at initialization, as this process is done entirely by the Proxy in vue3 source code.

Vue3 also offers a syntax that is closer to native JS, like !!!!!!

<script setup>
import { reactive, ref} from "vue";

// Incremental update: ref API
let val = ref("");
let todos = reactive([
  {
    id: 0.title: "Eat".done: false}, {id: 1.title: "Sleep".done: false,}]);function addTodo() {
  todos.push({
    id: todos.length,
    title: val.value,
    done: false}); val.value ="";
}
</script>
Copy the code

In fact, here, the students of VUE technology stack must be secretly proud, jump out a vUE yes! Vue3 uses the Proxy Api to solve these problems, but it also introduces new problems. Reactive can only transfer objects (react useState values are available), while ref (official recommendation) requires.value to obtain values. This has caused the community to fry. Therefore, the VUE team is forced to launch toRefs. I had a discussion with Ea before).

5. Event handling (@click vs onClick)

vue

The v-on (short for 🙂 directive is used in vue to listen for DOM events and run some JavaScript code when triggered. Typically, v-ON is used to receive a method name that needs to be called.

<div  @click="helloShanghai">welcome</div>
<div  @click="helloShanghai('hello')">welcome</div>
Copy the code

To access native DOM events, you can explicitly pass $event into method

<div  @click="helloShanghai('hello', $event)">welcome</div>
Copy the code

The common element addEventListener, component $on

react

The React element’s event handling is similar to the DOM element’s, but there are a few syntactic differences:

  • ReactEvents are named in small camel case rather than pure lowercase.
  • useJSXSyntax you need to pass in a function as an event handler, not a string.
<div onClick={this.handleClick}>Click me</div>
<div onClick={this.handleClick.bind(this)}>Click me</div>
<div onClick={()= >{this. HandleClick ()})} > Click me</div>
<div onClick={this.handleClick()}>Click me</div><! -- Error >Copy the code

React mounts the composite event to the document,

6. Componentization

Vue encourages writing templates that are similar to regular HTML. It’s written pretty much like a standard HTML element, with a few more attributes. React recommends that all of your templates use JavaScript syntax extensions called JSX writing.

7. Build tools

React ==> Create React APP Vue ==> vue-cli

8, other

There are other comparisons, such as vue’s slots and React’s props. Children. Life cycle: getDerivedStateFormProps, getSnapshotBeforeUpdate

I’m so tired…

Fourth, my view

1. Vue is suitable for small and sophisticated projects, while React is more suitable for large projects. 2. React is recognized in large projects because it is more elegant than VUE in dealing with the reuse of complex logic or components. However, it also needs the overall strength of the team and the design and control capabilities of the leaders are better, so the development cost is higher. 3. Vue’s more user-friendly writing method stands out in small but sophisticated projects such as H5, and its friendlier API and user-friendly design greatly improves development cost and efficiency. 4. On the other hand, VUE regulates a lot of apis to standardize developers, but also restricts developers’ divergent thinking to some extent; React, on the other hand, improves developer creativity with fewer apis, while creating different code styles because each React developer has a different understanding of React.

How do you think about that?

Recall those years preschool end of the past, can not help but want to recite a poem.

Five, recite a poem

Technological change, ups and downs

We’ve seen how much jquery can do,

We’ve seen the React process evolve,

We saw the beginning of Vue,

We’ve seen NodeJS beat the bully.

The land is long and broad,

We can only ride the waves,

Despite all the changes in technology,

We can ride the field, too.

For those who are constantly learning and striving for their goals, September 7, 2021.

Six, the whole family bucket

react vue
The react – the router, the react – the router – dom vue-router
redux vuex
antd ElementUI, iview
redux vuex
next.js nuxt
The react – native, taro Uni – app, weex
antd-mobile Mint-ui, VUX, Vonic, cube-UI

Vi. Reference documents

The history of React. Js

React History

Why does React implement functional components now? Is it bad to use class?

Vue brief

What is the origin of the name vue. Js and why is it called vue?

React Diff algorithm

The getSequence of Vue3 is the longest ascending subsequence

Source code analysis of patch update process in Vue view

Vue – making the address

Force-link algorithm problem – the longest increasing subsequence

React lifecycle

Vue lifecycle hooks

【vue3.0】onRenderTracked and onRenderTriggered

Use of Watch and watchEffect in VUE3

The responsivity principle of VUE

React

Compare React and Vue without blowing or blackening

Deep into the responsivity principle

What are the pros and cons of Vue2 versus React?

Several practical VUE mobile UI framework

Do React and Redux update from the root?

Some Comparisons and Personal Reflections on Vue and React (1)

Some Comparisons and Personal Reflections on Vue and React (middle)