Why you may need to consider svelte.js over React,Vue or Angular
Tags: showdev, svelte, tutorial
Published: 2019-05-19 19:39:01

---
title: Why you may need to consider svelte.js over React,Vue or Angular
published: true
description: getting started with svelte.js by building a Todo Application
tags: showdev, svelte, tutorial
canonical_url : https://cloudnweb.dev/2019/05/why-you-may-need-to-consider-svelte-js-over-reactvue-or-angular/
---
To Support my Work - Read this post from <a href="https://cloudnweb.dev/2019/05/why-you-may-need-to-consider-svelte-js-over-reactvue-or-angular/"> original source </a>
<!-- wp:image {"id":492,"align":"center","width":449,"height":390} -->
<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/oh_no.gif" alt="" class="wp-image-492" width="449" height="390"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>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. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let’s see what makes it special in this article.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is svelte.js ?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>&nbsp;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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Virtual DOM ?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Every Virtual DOM Object is mapped with the Real DOM Objects. Instead of Manipulating the Real DOM, Virtual DOM gets changed.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":493} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/v_dom-1024x380.png" alt="" class="wp-image-493"/><figcaption>Source : https://medium.com/@rajaraodv</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Read More about <a href="https://medium.com/@rajaraodv/the-inner-workings-of-virtual-dom-666ee7ad47cf">Virtual DOM</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Overhead of Virtual DOM :&nbsp;</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>&nbsp;React brings the concept of Virtual DOM Diffing. Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM&nbsp;<em>snapshot</em>&nbsp;that was taken right before the update.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>By comparing the new virtual DOM with a pre-update version, React figures out&nbsp;<em>exactly which virtual DOM objects have changed.</em>&nbsp;This process is called “diffing.”</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Most obviously,&nbsp;doffing isn’t free. You can't apply changes to the real DOM without first comparing the new virtual DOM with the previous snapshot.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is where svelte shines. Svelte solves the problem without a need of virtual DOM.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://svelte.dev/blog/virtual-dom-is-pure-overhead">Svelte Feature</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Svelte.js - Getting Started :</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this article, we will see how to create a To-do List application in svelte.js</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, we will install svelte.js and create a starter project using command line.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npx degit sveltejs/template my-svelte-project
cd my-svelte-project

npm install
npm run dev</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, the application will be running and when you visit the <strong>http://localhost:5000</strong> you will see <strong>Hello World</strong>  in the browser. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's see the folder structure and components in the svelte project</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":495,"align":"center","width":268,"height":390} -->
<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/Screen-Shot-2019-05-19-at-11.54.02-PM.png" alt="" class="wp-image-495" width="268" height="390"/></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li><strong>public</strong> - it contains the compiled code of the application. the web page that we see in the browser is rendered from this compiled code</li><li><strong>src</strong> - this folder contains all the code that we write for the application</li><li><strong>package.json</strong> - it is something like a meta data description which contains the dependencies used for the project</li><li><strong>main.js</strong> - This file is the root for the application .</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>As it said earlier, svelte is a component based framework. we will create components needed to create a to-do list application</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Svelte Component Structure:</h2>
<!-- /wp:heading -->

<!-- wp:image {"id":496} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/Screen-Shot-2019-05-20-at-12.04.10-AM-1024x615.png" alt="" class="wp-image-496"/><figcaption><strong>component structure</strong></figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>That's it .... Seriously. This is the Structure of a component. Pretty simple.right?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we can write all the component logic inside the &lt;script&gt; tag and all the styles in the&lt;style&gt; tag and remaining will be considered as a html elements.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Before writing any code for the application .we will see how we are going to build the to-do application. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":497} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/Screen-Shot-2019-05-20-at-12.11.55-AM-1024x462.png" alt="" class="wp-image-497"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Application can be separated as three components. </p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Todos Component</strong> - it contains the Custom Component List and input box</li><li><strong>TodoItem Component</strong> - it contains the Todo title and a button </li><li><strong>AddTodo Component</strong> - it contains the input box and a insert button</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>we will be using the mock server (json-server) to create a mock database. To know more about <a href="https://github.com/typicode/json-server">json server </a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file called <strong>db.json</strong> and add the following data for mock server</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>{
  "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
    }
  ]
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>create a file called <strong>Todos.svelte</strong> and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;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;	
	})
&lt;/script>

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

	&lt;AddTodo />
	&lt;div class="ui container mtop">

	&lt;div class="ui middle aligned divided list">
		{#each todosData as todo}
		    
			&lt;TodoItem  title={todo.title} id={todo.id} isCompleted={todo.iscompleted}/>	
		{/each}
	&lt;/div>
&lt;/div></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>TodoItem and AddTodo are child components that we import into our parent. <strong>onMount</strong> and <strong>afterUpdate</strong> are life cycle event of svelte. To Read about life cycle event , <a href="https://svelte.dev/tutorial/onmount">Life Cycle Events</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In Life cycle event we make an API call to fetch the data and pass it to the <strong>TodoItem</strong> child component.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file called <strong>TodoItem.svelte</strong> and add the following code </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;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);
   }
&lt;/script>

&lt;style>
    .completed{
        background : green;
    }
&lt;/style>

&lt;div class="item">
{#if isCompleted }

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

    &lt;div class="content">
        {title}
    &lt;/div>
{/if}			   
&lt;/div></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, we make an <strong>onclick</strong> button event which marks the todo as completed.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file called AddTodo.svelte and add the following code . </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;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 = '';
    }

&lt;/script>


&lt;style>

&lt;/style>


&lt;div class="ui fluid action input">
		&lt;input type="text" bind:value={titleValue} placeholder="Enter todo...">
		&lt;div class="ui button" on:click={() => addTodo(titleValue)}>Add&lt;/div>
&lt;/div></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>one of the important features of Angular is <strong>Two-way data binding</strong>. svelte uses some <a href="https://svelte.dev/tutorial/text-inputs">similar feature</a> which binds the javascript variable with the input value. whenever we changes the input value, the javascript variable gets updated.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;input type="text" bind:value={titleValue} placeholder="Enter todo..."></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, if we run the application in the browser, we can able to access the simple to-do application.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":499} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/Screen-Shot-2019-05-20-at-12.11.55-AM-1-1024x462.png" alt="" class="wp-image-499"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>complete source code of this application can be found here . <a href="https://github.com/ganeshmani/svelte-todo">Svelte Demo</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Reference : </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://svelte.dev/tutorial/basics">Svelte Documentation</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To Read more about <a href="https://cloudnweb.dev/category/web-dev/">web development</a></p>
<!-- /wp:paragraph -->