Vue vs React: Battle of the Javascript Frameworks

FavoriteLoadingAdd to favorites

As we’ve mentioned before here, the WordPress core team is debating which JavaScript framework to add to the existing set of frameworks. React and Vue.js appear to be front-runners, with many members of the community discussing the pros and cons of these two frameworks.

So which framework rocks and which framework is the new prototype.js.? Let’s find out.

I’ve created two nearly identical sample applications, one in Vue and one in React, if you’d like to give either framework a shot in the context of the samples in this article.

The Contenders

Unless you’ve been hiding under a rock for the past couple years, you’ve likely heard of the JavaScript UI framework developed at Facebook called React. It powers most of the Facebook website as well as Instagram. React was a bit of change in the JavaScript world when it came out as it’s quite different from other at-the-time frameworks like jQuery, Backbone.js and Angular 1. The biggest difference is that React popularized a Virtual DOM (we’ll get into this later) and created a new syntax called JSX that allows developers to write HTML in JavaScript. WAT?

Vue.js is a similar JavaScript framework that aims to tackle the same problems as React but in a different way. Vue uses a template system instead of JSX, arguably making it easier to integrate into existing apps. Because the templates use regular HTML Vue can be integrated into existing code quite easily, without the need for a build step. Vue is also said to be easier for new developers to pick up as well – something that I’ve recently verified as I’m new to Vue. The other main thing to mention about Vue is that it’s mostly maintained by a single developer rather than being backed by a large corporation like Facebook.

Similarities

React and Vue have a lot in common as they’re both UI JavaScript frameworks focused solely on creating rich front-end experiences. Unlike earlier JavaScript frameworks that had ‘batteries included,’ both React and Vue are fairly barebones with functionality like routing and state management handled by separate frameworks.

Usage of a Virtual DOM

Ahh, the oft spoken-about Virtual DOM.

DOMS, DOMS EVERYWHERE

One of the biggest similarities between Vue.js (as of version 2.0) and React is the usage of what’s called a ‘Virtual DOM’. A Virtual DOM is basically what it sounds like, a virtual representation of the DOM tree. It hinges on the concept that updating the real DOM frequently is computationally heavy. Updating JavaScript objects is relatively lightweight by comparison.

With a Virtual DOM, a JavaScript object representing the real DOM tree is created. Updates to any element are made in the Virtual DOM rather than the real DOM. When something is changed, a new Virtual DOM object is created and the changes between the old and new are determined. These changes are then applied to the real DOM.

For example let’s take this list in HTML:

  • item 1
  • item 2

In JavaScript this could be represented simply as:

{
    type: 'ul', 
    props: {'class': 'list'}, 
    children: [
        { type: 'li', props: {}, children: ['item 1'] },
        { type: 'li', props: {}, children: ['item 2'] }
    ]
}

Actual Virtual DOM implementations are more complex than this, but they’re essentially a nested JavaScript object with nested arrays.

When a new item is added to this JavaScript object a function will ‘diff’ the changes and apply the new markup to the real DOM. This ‘diffing’ algorithm is the secret sauce, and both React and Vue do this a bit differently.

Vue is reported to be able to diff changes to the Virtual DOM more quickly as it keeps track of each component’s dependencies during render, not needing to re-render a whole component’s sub-tree.

With React, child components will all be refreshed each time application state is changed. This can be overridden by using the shouldComponentUpdate lifecycle method, but Vue handles this kind of optimization by default.

Note: Using a Virtual DOM is only a good idea if you’ve got a large application making many updates to the UI. If you’re only updating elements infrequently it’s probably overkill and could very likely be slower than updating the DOM directly.

Component Based Architecture

Both React and Vue encourage a component based architecture. This essentially means separating your application into distinct chunks of related functionality with a defined way for each chunk to ‘talk’ to each other. A good explanation of what a component is can be found in this Medium article:

You can think of a component as a small feature that makes up a piece of the user interface. If I were to describe a component within the scope of Facebook’s UI, A chat window would be a component, a comment feed would be another component, and a constantly updating friend list would represent yet another component.

In Vue, you can use single file components that follow this principle.

//PastaItem.vue


  • {{this.item.name}}

    {{this.item.desc}}

    {{this.orders}}
  • export default { name: 'pasta-item', props: ['item'], data: function(){ return{ orders: 0 } }, methods: { addToOrderNew: function(y){ this.orders += 1; this.$emit('order'); } } }

    As you can see in the above example HTML, JavaScript and CSS are combined in one file. You don’t have to include CSS in your component .vue files, but it’s an option.

    In React it’s very similar, with JavaScript and that fun JSX markup in a component file.

    import React from "react";
    
    class PastaItem extends React.Component {
    
        render() {
            const { details, index } = this.props;
    
            return (
                
  • {details.name}

    {details.name}

    {details.desc}

    {this.props.orders || 0}
  • ); } } export default PastaItem;

    Props

    As in the above example, both React and Vue have a concept of ‘props’, which is short for properties. These are special attributes on an element that allow for the passing of data from parent to child.

    Object.keys(this.state.pastadishes).map(key =>
        
    )
    

    In the above JSX example the index, key, details, orders and addToOrder attributes are props passing data to the child PastaItem component.

    In React this is necessary as it relies on a local ‘state’ (more on that later) that acts as a ‘single source of truth’.

    In Vue, props are slightly different. They’re defined on a component in the same way, but since Vue relies on a template syntax, how you pass in data is a little more tricky and you have to use the built-in template loop functions.

    
    

    It’s a little more on the ‘templatey’ side of things, but it gets the job done and I find it about as complex as the React version.

    Build Tools

    Both React and Vue have bootstrap applications that get you up and running quickly with your development environment. In React this is Create React App (CRA) and in Vue it’s vue-cli. In both cases you get a project template set up according to the latest best practices.

    With CRA you’re a little more handcuffed as far as options. It’s an opinionated tool, forcing you to use Webpack and Babel out of the box. With vue-cli, you have options in the form of templates which makes it a little more flexible.

    In reality though, both bootstrap tools are awesome and give you a solid and modern starting point to get you coding. Anything that doesn’t make you configure Webpack is a win in my (and Jeff’s) book.

    enter image description here

    Chrome Devtools

    Both React and Vue also have awesome Chrome extensions to help in debugging. They let you inspect your application as you would any other website, but they allow you to see the Vue or React version of the markup. You’re also able to see application state data and see updates happen in real time.

    React devtools in action:

    Vue devtools in action:

    Companion Frameworks

    One last similarity (and difference) between these two frameworks is how they handle companion frameworks. Both React and Vue are focused solely on the UI layer, and leave functionality such as routing and state handling to companion frameworks.

    The difference between Vue and React is how they relate to their respective companion frameworks. The Vue core team maintains the vue-router and vuex frameworks and keeps them under the main Vue umbrella. React’s react-router and react-redux are maintained by community members and aren’t ‘officially’ under the Facebook/React umbrella.

    Main Differences

    While Vue and React have a lot in common, there are some major differences.

    Templating vs JSX

    The biggest difference between React and Vue is how templating is done. In Vue, you’re encouraged to use regular-old-HTML for templating. This approach leverages custom attributes on standard HTML elements.

    • {{ item.msg }}

    The attributes can also be used on single file components, although it requires a build step to convert the component syntax to valid JavaScript and HTML.

    Vue encourages the use of HTML to render things, while it uses a familiar Angular-style method for outputting dynamic content with Mustache-style syntax. For this reason, Vue is arguably easier to integrate into existing applications as you can very simply incorporate Vue templates into existing templates without too much overhead. This also reportedly makes it easier for newcomers to adapt to this syntax.

    React on the other hand recommends you write all your template code in JavaScript by using a ‘syntax extension to JavaScript’ called JSX. For example, the same code in JSX:

      { Object.keys(this.state.pastadishes).map(key => ) }

    React/JSX definitely appears more verbose at first glance, but by adding the ability to use JavaScript within templates a lot more power is given to the developer.

    But remember:

    With great power comes great responsibility. Ben Parker

    JSX is really just JavaScript with some funny XML syntax. However, once you get used to it, it feels a lot more flexible and robust. This might be my own biases coming through, but I feel this is a better approach as I was never a fan of the Angular 1 style attribute mess.

    The counter argument is that Vue’s template syntax removes the temptation to pile additional logic into your views/components, maintaining a separation of concerns.

    It should also be mentioned that Vue does technically support render functions and JSX, like React, but they’re not the default approach.

    State Management vs Object Properties

    If you’re familiar with React you’ll know that application state is a key concept. There’s even frameworks dedicated to managing large scale state objects like Redux. Additionally, state data in React applications is immutable, meaning that it can’t be changed directly (though this isn’t exactly true). In React you need to use the setState() method to modify anything in the local state.

     addToOrder(key) {
            //Make a copy of this.state
            const orders = { ...this.state.orders };
    
            //update or add
            orders[ key ] = orders[ key ] + 1 || 1;
            this.setState( { orders } );
     }
    

    With Vue a local state object isn’t required, and data is managed via the data property on the Vue object.

    export default {
      name: 'app',
      data() {
        return {
          samplePasta: samplePasta,
          orders: {}
        }
      },
    ...
      methods: {
        handleOrder: function (key) {
    
          if (!this.orders.hasOwnProperty(key)) {
            this.orders[key] = {count:0};
          }
    
          this.orders[key].count += 1;
        }
      }
    }
    

    In Vue there’s no need to call a state management function like setState(), as the data parameter on the Vue object acts as the holder for application data.

    On the topic of state management for large scale applications, Evan You, creator of Vue.js, has said that these kind of solutions are suitable for small scale applications, but are not scalable for larger applications.

    In most cases, the built-in state management patterns provided by the frameworks themselves are insufficient for large scale apps, and a dedicated solution like Redux or Vuex must be used.

    With that in mind, arguing about how state is managed in your application is most likely a premature optimization, and, as with most things, it’s a matter of personal preference. Besides, you might not even need to worry about it.

    React Native vs. ?

    One area where React clearly has an advantage is the ability to create native mobile applications with React Native. The ability to use JavaScript, CSS and HTML to create legitimate native mobile apps is a game changer. The Vue community and e-commerce giant the Alibaba Group are working to create Vue’s version of React Native called Weex, but it’s still in development and clearly not as battle-tested.

    So who wins the battle?

    TLDR; JavaScript sux, use TypeScript

    If you’re in the market for a shiny new JavaScript UI framework, you can’t go wrong with either React or Vue. While React seems to be more popular, Vue is gaining popularity and isn’t going anywhere. If you’re looking to integrate a new JavaScript framework into an existing codebase, I’d give Vue a look. If you’re looking to build a mobile app with web technologies, React (for now) is the clear winner. In reality, either is a fine choice for building a modern JavaScript app and it really depends on which approach is more appealing to you.

    What are your thoughts on Vue and/or React? Let us know if the comments!

    P.S. Did you hear that after 2 years of 10 releases including 57 new features or improvements added, 44 bug fixes deployed, over 11,245 support emails answered and zero price increases, we’re increasing the price for WP Migrate DB Pro on June 22? Save $50 on all plans before then: https://deliciousbrains.com/wp-migrate-db-pro/

    The post Vue vs React: Battle of the Javascript Frameworks appeared first on Delicious Brains.

    Click to visit original source at DeliciousBrains.



    Categories: Wordpress

    Tags: , , , , , , , ,

    Subscribe

    Subscribe to this Journal

    Subscribe to our Saturday morning digest of each week's new content. ITS FREE!

    Email address