The comparison between React and VUE has always been a controversial topic. Perhaps every front-end has more or less participated in this debate, but valuable content produced in this huge debate has always been relatively scarce. I have no intention to cause another quarrel here, but I hope to illustrate as objectively as possible the differences and advantages between the two frameworks based on my own experience. In fact, comparing the two frameworks based on documentation and some demos is almost meaningless without actually using them in a production environment. I used VUE almost exclusively in my previous year’s work, because the technology stack of the previous company department was vUE only. Although I also learned React and made some demos according to the documents, However, when I really wanted to know the specific difference between React and VUE and read some articles about React, I found that it was difficult to really figure out the real difference between react and VUE without practice and systematic study of React. However, after I have been writing React for about three months, the biggest discovery is that there are many differences between react and react, which will gradually rise to the surface of the water. Therefore, it is recommended that students with loose technology stack in the department should try more. The best way to figure out the problem is to try to solve it by themselves.

The opinions expressed below are personal and do not guarantee that they are correct

Diff, Patch and Update

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. React will still use diff to compare the virtual DOM twice and patch it to the real DOM. However, if the tree of components is too large, diff can actually have some overhead because the diff process is still comparing the entire tree of components at the root of that component. React provides a shouldComponentUpdate solution to determine whether the diff, patch, and update functions need to be performed. In the actual development process, we often use pureComponent to help us make this logical judgment, but it should be noted that pureComponent shouldComponentUpdate is only shallow comparison, suppose the type of comparison is object, ShouldComponentUpdate assumes that there is no change between an object if only its properties change but its references do not.

vue: The responsivity of vue uses the Object.definePropertyAPI, and because of the dependency collection implemented in the getter, it does not compare the whole tree of components like React, but updates components with a more granular state. DefineProperty also doesn’t have the problem of comparing references as shouldComponentUpdate does.

Contrast: Although React can achieve the same effect through shouldComponentUpdate, if the state hierarchy is deep, it will be more laborious to manually optimize this part of the code. So in React we need to keep the structure as flat as possible and let the pureComponent help us optimize it automatically.

How state data is changed

React: Since React and Redux both promote functional programming, similar state changes are similar to the following code

State = {obj: 2} {a: 1, b:, arr: [1, 2, 3],} / / modify obj. ModifyObj = b () = > {enclosing setState ({obj: {... This. State. Obj, b: 3,}})} / / modify arr modifyArr = () = > {enclosing setState ({arr: [... this. State. Arr, 4],})}Copy the code

B = 3 and setState({obj}). In some cases this doesn’t cause any errors. But first, because react and Redux are known to promote functional programming, So it’s officially not recommended to modify objects or arrays directly. Second remember we said above pureComponent, because shouldComponentUpdate is shallow, if directly modify the object or array can result in component will not be updated.

Vue: VUE is relatively easy to modify the state data. We can just use this.obj.b = 3 for the object. This will trigger the setter set for the first rendering, and notify all watcher to update. However, vUE is not so simple when it comes to modifying arrays. Although we can still modify arrays with push, unshift, etc., arr[index] = someVal does not work. Or map a new array and reassign it in a way like React. Recently, VUe3 has also gradually surfaced, and the latest vueConf announced that VUe3 uses proxy solution, so the array changes in VUe3 can use arR [index].

Comparison: In the case of data as the object, the code method of VUE is more simple and convenient, while in the case of array, there is no big difference between VUE and React, and we still use map,filter and other functions in most cases. React and Redux advocate always replacing old values with new ones in order to make it easier to debug and time travel, but this doesn’t conflict with vUE. You can write your VUE code this way if you like. By the way, although object.defineProperty seems to help vUE a lot, it is not without side effects. When the state data is large, the initial cost of vUE can be higher because the API needs to recursively listen on the state data. React has a longer blank screen than React. This problem is also solved in VUe3 because proxy-based listening is similar to lazy.

About Logic reuse

React: It’s an interesting thing to talk about logic reuse. It’s really interesting to talk about the React community and the quality solutions that the community contributes, from mixins to higher-order components to renderProps. We’ll use renderProps as an example, but higher-order components will be discussed later. The so-called logic complex is to reuse some common logic to the components that need these logic. Let’s take a look at the react official documentation for example.

This is a component that displays the mouse position in real time. The main logic for this component is the processing of mouse events, but this part is exactly the one that is difficult to reuse. Suppose we want to render a picture of a cat in another component, and its position is determined by the mouse position. So we’re basically going to have to write the mouse event and state code again to see how the renderProps are working.

The first time you look at this code, it’s a bit of a wonder how the hell it came to be. Abstracting out the behavior of the Mouse component and passing state as a parameter to the external function that returns the component is pretty cool. By the way, you don’t have to use render as props, as in this example we could have written it as code

<Mouse> {Mouse => <Cat Mouse ={Mouse} />} </Mouse> // Mouse component <div onMouseMove={this.handleMouse}>{this.props.children(this.state)}</div>Copy the code

Corresponding to this, we can make many such encapsulation, such as the switch of the modal box, such as Input, Select and other controls on onChange and setState encapsulation, a simple example

<Container>
{
    (value, changeValue) => <Input value={value} onChange={changeValue} />
}
</Container>
Copy the code

Imagine a common scenario with four inputs and a Button search Button, and then display the searched data on a table. Using this encapsulation saves a fair amount of boilerplate code.

Vue: Let’s see how VUE implements the mouse reuse logic above.

/ / instructions Vue. Directive ('mouse', {
  binding: function (el, binding) {
    function mouseMove(e) {
        binding.value.x = e.clientX;
        binding.value.y = e.clientY;
    }
    el.__mouseMove = mouseMove;
    el.addEventListener('mousemove', mouseMove);
  },
  unbinding: function (el) {
      el.removeEventListener('mousemove', el.__mouseMove); <template> <div v-model="data">
        {{ data.x }}, {{ data.y }}
    </div>
</template>
Copy the code

Register a v – mouse commands directly, we can in any components to reuse the logic, actually single theory this two pieces of code I personally think that the realization of the vue is better, v – mouse this declarative instruction is very clear and elegant, but but but we must know this is just a piece of logic is very simple, if more complex logic, There’s no doubt react is much more flexible and maintainable than instructions.

Contrast: React’s renderProps are a bit more cumbersome but definitely better than Vue’s instructions in terms of flexibility and maintainability. However, vUE directives can be quite convenient in some simple scenarios, such as the most commonly used built-in V-model. Still think of the scenario we described earlier, multiple Input and a button, vUE corresponds to only four V-models =”value”.

Flow of data

This is not the difference between the two, but many people instinctively react to two-way data binding when they see a V-Model. Many of the responses that compare VUE and React to this day say that due to vUE’s two-way data binding, data tends to become cluttered and difficult to maintain in large projects, which is a bit of a joke. In fact, the data flow between vUE and React components is one-way from parent to child, and the child components are not allowed to change props. There is no difference between the two components, while v-model in input is just a way of logic reuse or declarative syntax sugar. Again, using v-Models for components is a syntactic sugar, but the flow of data is still clearly one-way.

High order component

React: High-order components are another form of reuse logic. Compared to renderProps, high-order components actually choose what to pass in, while renderProps expose what to leak. So-called high order component with higher-order functions actually is a meaning, just receive is a component and then returns a component, a common example, assume we have a interface tree is to get the company’s organization, the organization should use in many situations, we can take out a common high-order component

function HOC(wrapperComponent) {
    return class getOrgTree extends React.Component {
        state = { orgTree: [] }
        
        componentDidMount() {
            fetch('xxxxxxx').then(orgTree => this.setState({ orgTree }))
        }
        
        render() {
            return<wrapperComponent orgTree={this.state.orgTree} {... this.props} /> } } }Copy the code

This function allows us to pass any of our own components into the function to have props of orgTree. In addition, we can use higher-order components to reduce or increase props and other extensibility operations

Vue: Similar operations of VUE can only be implemented through mixins (easy to pollute and debug), and it is even more difficult to expand mixin components. The difference between the two is that react components change body with a layer of armor, while VUE components just take things and put them in the pocket, which is essentially their own.

const myMixin = {
  created: function () {
    fetch('xxxxx').then(orgTree => this.orgTree = orgTree)
  },
}
Copy the code

Contrast: At the stage of high-order functions react still achieves high scalability and flexibility through object-oriented approach. Vue has little room to play in high-order functions, because Vue is actually oriented to configuration (options). Although we can use render function to write something that looks like high-order components, However, first of all, the code written by Render is very unreadable (although it seems possible to write JSX with Babel, but then why not use React directly), and second, it almost deviates from the development mode of Vue, so react is actually leading in terms of mode application and logical reuse. The good news is that vue3’s components are now class, which may help vue improve on this shortcoming.

TypeScript support

Contrast: Vue2 is supported, but not very good at using react. It lags many levels behind React. Vue3 still solves the problem.

Community and surrounding ecology

Contrast: In fact, I think a big part of the difference between React and VUE lies in the community and some ecology. React community contribution is really quite active, with various solutions and mature components (not only UI library), while VUE is much quieter and many components are not of high quality. This is not a problem vuE3 can solve, the only thing that can depend on is time.

conclusion

The conclusion is the same with many comparisons. Vue is suitable for small and sophisticated projects, while React is more suitable for large projects. However, the fulcrums to stand on this conclusion are different. But in small and exquisite, more friendly way of writing vue, simplify the code and more declarative instructions are great advantages and characteristics, and instead of the react in large project can better complete the shortage of the vue, but also need more technical team as a whole is to force, leading the design and control of power is more outstanding, Bad design might be worse than no design at all. Some people always think that vUE has more API and more flexible writing, which makes it difficult to maintain the final code. In fact, React may be the more flexible one, because React has almost no API, so it is feasible to write code no matter what. There are 10 people in the team may have 10 ways to understand React. In addition, whether it is state management, asynchronous middleware, routing, etc., react community provides more options, how to choose and which solution to use is also a bit of a headache.

The last

Original address: github.com/wangweida/b…

It is not too much to give a star after reading this