Why you may need to consider svelte.js over React,Vue or Angular

ganeshmani

GaneshMani

Posted on May 19, 2019

Why you may need to consider svelte.js over React,Vue or Angular

To Support my Work - Read this post from original source

I know. I know. you may think of like why do I need to learn an another Framework?. but there is something unique that svelte has which makes stands out from other frameworks.

Let’s see what makes it special in this article.

What is svelte.js ?

 Above all, Svelte.js is a Component Framework like React and Vue but with an important difference. React uses a technique called VirtualDOM which we will cover later in this article.

In simple terms, React allows us to write a state-driven code which gets converted by browser into ideal javascript code .it can be a pain because most of the conversion happens in the browser whereas svelte converts the code into ideal javascript code at build time rather than doing it at run-time. 

What is Virtual DOM ?

Manipulating Real DOM is slow. Let’s say we have a list with ten items in it. When, one item gets changed, we need to re-render all the ten items. Consider in a modern website where we have lots of DOM manipulation which makes the application slow. 

To solve this problem, React Team came up with a solution of Virtual DOM which is similar to DOM Objects, but it lacks the ability to change anything on the screen.

Every Virtual DOM Object is mapped with the Real DOM Objects. Instead of Manipulating the Real DOM, Virtual DOM gets changed. 

Source : https://medium.com/@rajaraodv

Read More about Virtual DOM

Overhead of Virtual DOM : 

 React brings the concept of Virtual DOM Diffing. Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update.

By comparing the new virtual DOM with a pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called “diffing.”

Most obviously, doffing isn’t free. You can't apply changes to the real DOM without first comparing the new virtual DOM with the previous snapshot.

This is where svelte shines. Svelte solves the problem without a need of virtual DOM.

Svelte Feature

Svelte.js - Getting Started :

In this article, we will see how to create a To-do List application in svelte.js

Firstly, we will install svelte.js and create a starter project using command line.

npx degit sveltejs/template my-svelte-project
cd my-svelte-project

npm install
npm run dev

Now, the application will be running and when you visit the http://localhost:5000 you will see Hello World in the browser.

if you have experience in working with React or Vue. it will be a cake walk for you. if you are haven't, don't worry. you are in a right place at right time.

Let's see the folder structure and components in the svelte project

  • public - it contains the compiled code of the application. the web page that we see in the browser is rendered from this compiled code
  • src - this folder contains all the code that we write for the application
  • package.json - it is something like a meta data description which contains the dependencies used for the project
  • main.js - This file is the root for the application .

As it said earlier, svelte is a component based framework. we will create components needed to create a to-do list application

Svelte Component Structure:

component structure

That's it .... Seriously. This is the Structure of a component. Pretty simple.right?

we can write all the component logic inside the <script> tag and all the styles in the<style> tag and remaining will be considered as a html elements.

Before writing any code for the application .we will see how we are going to build the to-do application.

Application can be separated as three components.

  • Todos Component - it contains the Custom Component List and input box
  • TodoItem Component - it contains the Todo title and a button
  • AddTodo Component - it contains the input box and a insert button

we will be using the mock server (json-server) to create a mock database. To know more about json server .

create a file called db.json and add the following data for mock server

{
  "todos": [
    {
      "id": 1,
      "title": "Check one",
      "iscompleted": false
    },
    {
      "id": 2,
      "title": "Check two",
      "iscompleted": false
    },
    {
      "id": 3,
      "title": "Check three",
      "iscompleted": false
    },
    {
      "id": 4,
      "title": "Check four",
      "iscompleted": false
    },
    {
      "id": 5,
      "title": "Check Five",
      "iscompleted": false
    }
  ]
}

create a file called Todos.svelte and add the following code

<script>
        import TodoItem from './TodoItem.svelte';
    import AddTodo from './AddTodo.svelte';
    import { onMount,afterUpdate } from 'svelte';
    export let name;

    let todosData = [];

    onMount(async ()=> {

    let response = await fetch('http://localhost:3000/todos');
        let result = await response.json();
    todosData = result;
        
    })

    afterUpdate(async ()=> {

         let response = await fetch('http://localhost:3000/todos');
         let result = await response.json();                  
         todosData = result;    
    })
</script>

<style>
    h1 {
        color: purple;
    }
    .mtop{
        margin-top : 15px;
    }
</style>

    <AddTodo />
    <div class="ui container mtop">

    <div class="ui middle aligned divided list">
        {#each todosData as todo}
            
            <TodoItem  title={todo.title} id={todo.id} isCompleted={todo.iscompleted}/>  
        {/each}
    </div>
</div>

TodoItem and AddTodo are child components that we import into our parent. onMount and afterUpdate are life cycle event of svelte. To Read about life cycle event , Life Cycle Events

In Life cycle event we make an API call to fetch the data and pass it to the TodoItem child component.

create a file called TodoItem.svelte and add the following code

<script>
   export let id;
   export let title;
   export let isCompleted;

   async function handleClick(id,title){

       let data = {
           id : id,
           title : title,
           iscompleted : true
       }
       let response = await fetch(`http://localhost:3000/todos/${id}`,{
           method : 'PUT',
           headers : {
               'content-type' : 'application/json'
           },
           body : JSON.stringify(data) 
       });

       let result = await response.json();
       console.log(result);
   }
</script>

<style>
    .completed{
        background : green;
    }
</style>

<div class="item">
{#if isCompleted }

    <div class="content completed">
            {title}
    </div>
{:else }
    <div class="right floated content">
        <div class="ui button" on:click={() => handleClick(id,title)}>Mark as completed</div>
    </div>

    <div class="content">
        {title}
    </div>
{/if}              
</div>

Here, we make an onclick button event which marks the todo as completed.

create a file called AddTodo.svelte and add the following code .

<script>
    let titleValue = '';

    async function addTodo(title){

          let data = {
           title : title,
           iscompleted : false
       }
       let response = await fetch(`http://localhost:3000/todos`,{
           method : 'POST',
           headers : {
               'content-type' : 'application/json'
           },
           body : JSON.stringify(data) 
       });
       let result = await response.json();
        
        titleValue = '';
    }

</script>


<style>

</style>


<div class="ui fluid action input">
        <input type="text" bind:value={titleValue} placeholder="Enter todo...">
        <div class="ui button" on:click={() => addTodo(titleValue)}>Add</div>
</div>

one of the important features of Angular is Two-way data binding. svelte uses some similar feature which binds the javascript variable with the input value. whenever we changes the input value, the javascript variable gets updated.

<input type="text" bind:value={titleValue} placeholder="Enter todo...">

Now, if we run the application in the browser, we can able to access the simple to-do application.

complete source code of this application can be found here . Svelte Demo

Reference :

Svelte Documentation

To Read more about web development

💖 💪 🙅 🚩
ganeshmani
GaneshMani

Posted on May 19, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related