VueJS fundamentals + resources for React Developers

Estee Tey - Sep 11 '21 - - Dev Community

Introduction

This blog post aims to teach you about the fundamental concepts of VueJS from a React developer's perspective so that you can use your existing knowledge of components to easily pick up VueJS and add this framework into your skillset.

To get the most out of this post, itโ€™s best if you know the basics of implementing components - especially in React. This includes the 3 primary composable behaviours of components that were mentioned by the React documentation - State, Rendering, and Lifecycle.

https://community.codenewbie.org/remoteimages/uploads/articles/8kyzdlnba69hwfpyngdy.png

If you're not familiar with the above, you can check out a 5-min article that I previously wrote on Atomic Design for developers to learn the perspective of designing and structuring your components, since Vue is also a component-based frontend framework.

โ›ณ This is an important topic because VueJS is one of the most popular frontend frameworks. This year in 2021, at the time of this writing, it has more Github stars โญ (183k) than the ReactJS library (163k).

https://community.codenewbie.org/remoteimages/uploads/articles/dsup5cndar4ne4bm30pk.png

Picture retrieved from timqim using starhistory

In this article, I assume that you are already sold into the idea of learning a new framework, and that I do not have to go in depth into the detailed comparison between the pros and cons of the two frontend frameworks. Although if you are still keen in the compound benefit analysis of the frameworks, you can refer to the links that I have provided in the resources section at the end of the article.

From a pragmatic standpoint, at present, the number of jobs available for React developers is significantly larger than those for Vue. However, that doesn't undermine the value of Vue frontend framework. There are companies such as Alibaba, Netflix, Adobe and even Facebook (the creator of React) that uses Vue for their apps. There is also a write-up by a company that has migrated from using React to Vue.


Context on the code examples in this article

You can choose to skip this section and jump to the next if you just want to see the concepts in action already. Otherwise, it will be good for u stay on and understand what exactly is the code that you are reading ๐Ÿ˜†

For easier signposting of what you are reading, I will be adding the following emojis for its corresponding code:

  • ๐Ÿ“˜ = React
  • ๐Ÿ“— = Vue

For React ๐Ÿ“˜, I'll show you both the Class-based & Functional component code.

Below are some points that are helpful if you are a returning React developer who used to only write class-based components or if you are new to React and only know how to write functional components.

  • React from v16.3 onwards advocates the use of react functional components and function hooks over class-based components. For the returning developers, don't worry, the use of functional components is still compatible when used with class-based components.
  • If you are curious about the current state, many developers prefer the functional way of writing, and many React documentation has been updated to write functional components rather than class-based components (so new-comers may not know how to write class-based).
  • However, many production projects still use the class-based component way of writing, because they are massive and will take considerable effort in rewriting the code. It will also take those companies to re-skill their developers in learning the different APIs and hooks available.
  • Hence, at the moment, if possible, you should still know about both, unless you know for sure that the project you will be in will be using only 1 specific way of writing. I practice what I teach so that is also why I'm providing both.

for Vue ๐Ÿ“—, I'll show you the single-file component (SFC) syntax for the code examples.

  • This syntax is easier to understand compared to as long you have looked at some vanilla Javascript code before (I hope you are unlike me - I learnt React before JS ๐Ÿ˜…)
  • This syntax is also recommended by Vue for many reasons indicated in the link
  • I'll include the <template> and <style> parts only if those portions are necessary for the concept to make it easier for you to see the relevant parts

Now, let's begin!


State

Setting a default state

The state contains any mutable data attribute that you want the component to store. For example, it could be a loading boolean attribute, or even a more complicated object like user. Let's take these two things out and set it as a defaultState object.

const defaultState = {
    loading: false,
    user: {
        name: "John Smith",
        email: "js@codenewbie.com"
}
Enter fullscreen mode Exit fullscreen mode

In React, then you can store the state accordingly depending on whether you are using a class-based component or a functional component.

๐Ÿ“˜ Class-based component

import { Component } from 'react';

const defaultState = {
    loading: false,
    user: {
        name: "John Smith",
        email: "js@codenewbie.com"
}

class UserProfile extends Component {
    this.state = defaultState

    render() { //... }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“˜ Functional component

import { useState } from 'react';

const defaultState = {
    loading: false,
    user: {
        name: "John Smith",
        email: "js@codenewbie.com"
}

const UserProfile = () => {
    const [loading, setLoading] = useState(defaultState.loading);
    const [name, setName] = useState(defaultState.user.name);
    const [email, setEmail] = useState(defaultState.user.email);

    return ( //... )
}
Enter fullscreen mode Exit fullscreen mode

In Vue, you can also store the state in data().

๐Ÿ“— SFC syntax

<script>
export default {
    name: "UserProfile",
    data() {
        const defaultState = {
            loading: false,
            user: {
                name: "John Smith",
                email: "js@codenewbie.com"
        }
        return defaultState;
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Props & Computed Properties

Previously we defined a default state consisting of a user object & boolean for loading. However, for components to be reusable, they should be like functionsโ†’ take in some input and give out some output. In the context of frontend components, they will receive such "input" in the form of props. Props are data values that are passed down from the parent component to the child component.

In both Vue & React, setting your state values to be the same as your props is considered an anti-pattern since it will mean that you are duplicating values - making the source of truth ambiguous. Rather, it is more common to create computed properties based on the props you receive.

An example of a computed property will be:

const computedProperty = `${props.user.name} (${props.user.email})`
// so the result will be "John Smith (js@codenewbie.com)"
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“˜ In React, usually this is just a variable in both functional & class-based components. But for class-based components, the variable is placed in the render() method.

class UserProfile extends Component {
    this.state = defaultState

    makeFormattedUsername = (user) => {
        return `${user.name} (${user.email})`
    }

    render() { 
        const formattedUsername = this.makeFormattedUsername(this.props.user);

        return (...)
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“— In Vue, there is a specific computed() method to place such computed properties. You would also need to declare the props explicitly.

<script>
export default {
    data() { ... },
    props: [user],
    computed() {
        return {
            formattedUsername: `${this.user.name} (${this.user.email})`
        }
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

With the different methods, at a glance, you would know what this component is intended to do ๐Ÿ˜„


Mutating the state variables

We will want to change the data that we are storing and showing with component at some point, and the state is typically intended to be mutated with either of these 3 primary conditions:

  1. Change in props
  2. Change in watched object/events
  3. Change in lifecycle stage

The 3rd point will be covered in the next section, where you will learn about different lifecycle stages and methods available.


Lifecycle

There are 3 main stages of a component's lifecycle you should care about

  1. Mounting (Create)
  2. Update
  3. Destroy

In many component-based frameworks, they prefer to refer to those stages as

  1. Mounting
  2. Updating
  3. Unmounting

In both React and Vue, components have specific lifecycle hooks that you can call so that you can interact with the component at those specific points of mounting, updating and unmounting.


At a glance

โš ๏ธ Do not fixate on the specific details of the diagrams below, they are there to assist you in understanding each specific lifecycle stage of the component in the respective framework, but you need not memorize or fully understand them.

React Lifecycle Hooks

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ogimage.png

Retrieved from React Lifecycle Methods Diagram interactive site

  • ๐Ÿ“ At the interactive website, you can click on the buttons to be redirected the documentation for the specific lifecycle method method to refresh your memory!

Vue Lifecycle Hooks

The original Vue Lifecycle diagram can be found here, but it looks very confusing for a beginner so I made one that is simpler, that just comprises of the lifecycle hook methods in red.

VueJS_Chart_(1).png

They look pretty similar right? ๐Ÿ˜„


Other good to knows

Elegant passing of props

<blog-post v-bind="post"></blog-post>
Enter fullscreen mode Exit fullscreen mode

is equivalent to

<blog-post v-bind:id="post.id" v-bind:title="post.title"></blog-post>
Enter fullscreen mode Exit fullscreen mode

Naming of props, as described by documentation usually follow kebab-case standard, even if you declare a component to be named camel case like <BlogPost />

<blog-post post-title="hello!"></blog-post>
Enter fullscreen mode Exit fullscreen mode

Rendering

Thankfully, the rendering portion is quite abstracted for us in both frameworks such that we don't actually need to understand it in depth to make sure that our component renders.


Conclusion ๐Ÿป

This article has covered VueJS fundamentals in terms of the 3 main component concepts - State, Lifecycle and Rendering.

Remember that there is no silver bullet to everything ๐Ÿ’ซ , be it the coding style, the programming language as well as the tools available for use. React was once the most popular framework with VueJS trying to take over the lead now, but in future perhaps there's even more shiny new frameworks and tools coming up. As you advance further in learning about frontend frameworks in greater depth, you would start considering the specific use case of your project and trade-offs in deciding the framework. This also brings us to the next point on resources.

Resources ๐Ÿ“š

Now that youโ€™ve learned about the fundamental concepts of VueJS, take a look at these articles that cover Vue vs React in greater depth to understand better why developers may prefer Vue over React and vice-versa:

And if you're keen in jumping into Vue after this article, the following resources would be helpful:


Thanks for reading the article!

If you enjoyed reading it, react, feedback and follow me here and Twitter ! ๐ŸŒป๐Ÿฆ

. . . . . . . . . . . . . . . . . . . . . . . . . . . .