Why you need to consider svelte vs React,Vue or Angular

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. svelte vs react or any other frameworks.

Let’s see what makes it special in this article. svelte vs react or any other frameworks.

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 changes, 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.

v dom

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

Read More about Virtual DOM

Overhead of Virtual DOM : 

React brings the concept of Virtual DOM Diffing. Once react updates the virtual DOM , 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 “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.

1npx degit sveltejs/template my-svelte-project
2cd my-svelte-project
4npm install
5npm 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

Screen Shot 2019 05 19 at 11 54 02 PM

  • 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:

Screen Shot 2019 05 20 at 12 04 10 AM

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.

Screen Shot 2019 05 20 at 12 11 55 AM

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

2 "todos": [
3 {
4 "id": 1,
5 "title": "Check one",
6 "iscompleted": false
7 },
8 {
9 "id": 2,
10 "title": "Check two",
11 "iscompleted": false
12 },
13 {
14 "id": 3,
15 "title": "Check three",
16 "iscompleted": false
17 },
18 {
19 "id": 4,
20 "title": "Check four",
21 "iscompleted": false
22 },
23 {
24 "id": 5,
25 "title": "Check Five",
26 "iscompleted": false
27 }
28 ]

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

2 import TodoItem from './TodoItem.svelte';
3 import AddTodo from './AddTodo.svelte';
4 import { onMount,afterUpdate } from 'svelte';
5 export let name;
7 let todosData = [];
9 onMount(async ()=> {
11 let response = await fetch('http://localhost:3000/todos');
12 let result = await response.json();
13 todosData = result;
15 })
17 afterUpdate(async ()=> {
19 let response = await fetch('http://localhost:3000/todos');
20 let result = await response.json();
21 todosData = result;
22 })
26 h1 {
27 color: purple;
28 }
29 .mtop{
30 margin-top : 15px;
31 }
34 <AddTodo />
35 <div class="ui container mtop">
37 <div class="ui middle aligned divided list">
38 {#each todosData as todo}
40 <TodoItem title={todo.title} id={todo.id} isCompleted={todo.iscompleted}/>
41 {/each}
42 </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.

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

2 export let id;
3 export let title;
4 export let isCompleted;
6 async function handleClick(id,title){
8 let data = {
9 id : id,
10 title : title,
11 iscompleted : true
12 }
13 let response = await fetch(`http://localhost:3000/todos/${id}`,{
14 method : 'PUT',
15 headers : {
16 'content-type' : 'application/json'
17 },
18 body : JSON.stringify(data)
19 });
21 let result = await response.json();
22 console.log(result);
23 }
27 .completed{
28 background : green;
29 }
32<div class="item">
33{#if isCompleted }
35 <div class="content completed">
36 {title}
37 </div>
38{:else }
39 <div class="right floated content">
40 <div class="ui button" on:click={() => handleClick(id,title)}>Mark as completed</div>
41 </div>
43 <div class="content">
44 {title}
45 </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 .

2 let titleValue = '';
4 async function addTodo(title){
6 let data = {
7 title : title,
8 iscompleted : false
9 }
10 let response = await fetch(`http://localhost:3000/todos`,{
11 method : 'POST',
12 headers : {
13 'content-type' : 'application/json'
14 },
15 body : JSON.stringify(data)
16 });
17 let result = await response.json();
19 titleValue = '';
20 }
30<div class="ui fluid action input">
31 <input type="text" bind:value={titleValue} placeholder="Enter todo...">
32 <div class="ui button" on:click={() => addTodo(titleValue)}>Add</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 updates the variable.

1<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.

Screen Shot 2019 05 20 at 12 11 55 AM 1

svelte vs react or any other frameworks, check out the source code for the demo here. Svelte Demo

Reference :

Svelte Documentation

To Read more about web development

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...