Svelte vs. React: Differences When Building the Same Web App
Tags: svelte, javascript, react
Published: 2020-04-07 13:04:44

---
title: Svelte vs. React: Differences When Building the Same Web App
published: true
description: Svelte is an up-and-coming JavaScript library with much promise. But how does it compare to React? Let's build the same app with both libraries to find out!
tags: Svelte, JavaScript, React
canonical_url: https://blog.jscrambler.com/svelte-vs-react-differences-when-building-the-same-web-app/
cover_image: https://blog.jscrambler.com/content/images/2020/01/jscrambler-blog-svelte-vs-react.jpg
---

React is an extremely popular JavaScript library for building user interfaces while Svelte.js is a relatively new library for achieving the same things but with a different approach. 

Svelte borrows some ideas from React and Vue.js, but it brings its own approach for efficiency and performance. It gained some more momentum following the [2019 State of JavaScript survey](https://2019.stateofjs.com/front-end-frameworks/), which awarded Svelte with the “Prediction Award”.

From Svelte's own [website](https://svelte.dev/):

> Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.

So Svelte is a compiler more than a library. It runs at build time, compiling your components into plain JavaScript efficient code.

In this article, we'll build step by step a simple example using both tools.

## Prerequisites

Let's start with the prerequisites needed for working with both React and Svelte.

- Both libraries are based on JavaScript so familiarity with the language is required alongside with HTML and CSS;
- You need to have both Node 8+ and npm installed on your machine. You can use [nvm](https://github.com/creationix/nvm#installation) (macOS/Linux) or [nvm-windows](https://github.com/coreybutler/nvm-windows#node-version-manager-nvm-for-windows) to install and switch between Node versions in your system.

## Step 1: Installing React and Svelte 

Let's get started by installing the [create-react-app](https://github.com/facebook/create-react-app) tool and the [degit](https://github.com/Rich-Harris/degit) tool for initializing React and Svelte projects. 

Open a terminal and run the following commands:

```bash
npm install -g create-react-app
npm install -g degit
```

At the time of this writing, this will install `create-react-app` v3.3.0 and `degit` v2.2.2.

As we see, both React and Svelte have easy-to-install tools for quickly scaffolding new projects without the hassle of configuring any underlying build systems or tools.

## Step 2: Initializing React and Svelte Projects

Next, we'll proceed by initializing both the React and Svelte projects.

Head back to your terminal and initialize a React project using the following command:

```bash
create-react-app reactnewsapp
```

Next, navigate to your project's folder and serve it using the following commands:

```bash
cd reactnewsapp
npm start
```

Your app will be available from `http://localhost:3000/`.

This is a screenshot of what the app should look like right now:

<center><img src="https://blog.jscrambler.com/content/images/2020/01/jscrambler-blog-svelte-vs-react-create-react-app.png" alt="Create React App" style="box-shadow: 0 4px 20px #7f7f7f;"></center>

Next, let's initialize a Svelte app using the following command:

```bash
npx degit sveltejs/template sveltenewsapp
```

Next, navigate to your project's folder, install the dependencies and run the development server as follows:

```bash
cd sveltenewsapp
npm install
npm run dev 
```

You can access your app from `http://localhost:5000/` and it should look like this:

<center><img src="https://blog.jscrambler.com/content/images/2020/01/jscrambler-blog-svelte-vs-react-svelte-app.png" alt="Create Svelte App" style="box-shadow: 0 4px 20px #7f7f7f;"></center>

## Step 3: Understanding and Using Components

In modern front-end web development, a component refers to a reusable piece of code that controls a part of the app’s user interface.

In terms of code, it's made of a JavaScript class or function, HTML (optionally) for rendering the view and CSS for styling the view.

Components are the building blocks of both React and Svelte applications.

In React, you create a component by declaring a class that extends `React.Component`, inside a typical JS file, which provides [features](https://blog.jscrambler.com/stateful-vs-stateless-vs-pure-react-components/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react) for life-cycle events and state. You can also use functions to create components and [hooks](https://blog.jscrambler.com/introducing-react-hooks/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react) to access state and replace life-cycle events in functional components.
 
In Svelte, you create a component by creating  `.svelte` files, which contain a `<script>` tag, a `<style>` tag and some markup, but all three sections are optional. They are more similar to `.vue` files in [Vue.js](https://blog.jscrambler.com/introduction-to-vue/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react).

Go to the Svelte project, and open the `src/App.svelte` file which has the following code:

```svelte
<script>
	export let name;
</script>

<main>
	<h1>Hello {name}!</h1>
	<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
	main {
		text-align: center;
		padding: 1em;
		max-width: 240px;
		margin: 0 auto;
	}

	h1 {
		color: #ff3e00;
		text-transform: uppercase;
		font-size: 4em;
		font-weight: 100;
	}

	@media (min-width: 640px) {
		main {
			max-width: none;
		}
	}
</style>
```

You can also see that the component exports a `name` variable with the `export` keyword. This is how Svelte declares properties that are used to pass data from one component to its children. 

>**Note**:  This is not how `export` normally works in JavaScript modules. This syntax is specific to Svelte. 
   
Since our app is small, let's keep it simple and use the existing components to implement our functionality.

## Step 4: Fetching and Displaying Data     

Next, we'll see how to fetch and iterate over data in both React and Svelte.js.

Let's start with React. go to the `src/App.js` file and update it as follows:

```js
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  const apiKEY = "<YOUR-API-KEY>";
  const dataUrl = `https://newsapi.org/v2/everything?q=javascript&sortBy=publishedAt&apiKey=${apiKEY}`;
  
  const [items, setItems] = React.useState([]);

  const fetchData = async () => {

    
    	const response = await fetch(dataUrl);
    	const data = await response.json();
		  console.log(data);
      setItems(data["articles"]);
      
	
  };

  
  React.useEffect(() => {

    fetchData();

  }, []);


  return (
  <>
    <h1>
      Daily News
    </h1>
    <div className="container">
      
          {
            items.map(item => {
              
              return (
                			<div className="card">
                      <img src= { item.urlToImage } />
                      <div className="card-body">
                        <h3>{item.title}</h3>
                        <p> {item.description} </p>
                        <a href= { item.url } >Read</a>
                      </div>
                    </div>
              );
            })
          }
    </div>
    </>
  );
}

export default App;
```

<a href="https://blog.jscrambler.com/protecting-your-react-js-source-code-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react"><img alt="Protect your React App with Jscrambler" src="https://media.jscrambler.com/blog/V1-React.jpg"></a>

If you’re following this tutorial, don’t forget to get your own API key from the [News API website](https://newsapi.org/).

Open the `src/App.css` and add the following CSS styles:

```css
h1 {
	color: purple;
	font-family: 'kalam';
}
.container {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
	grid-gap: 15px;
}
.container > .card img {
	max-width: 100%;
}
```

Return back to your web browser, you should see an interface similar to this:

<center><img src="https://blog.jscrambler.com/content/images/2020/01/jscrambler-blog-svelte-vs-react-news-app.png" alt="Simples News App" style="box-shadow: 0 4px 20px #7f7f7f;"></center>

Now, let's build the same interface with Svelte. Open the `src/App.svelte` file.
 
Next, in the  `<script>`  tag, import the  `onMount()`  method from “svelte” and define the  `apiKEY`,  `items`, and  `dataUrl`  variables which will hold the news API key, the fetched news articles and the endpoint that provides data:

```javascript
<script>
	import { onMount } from "svelte";
    
	const apiKEY = "<YOUR-API-KEY>";
	const dataUrl = `https://newsapi.org/v2/everything?q=javascript&sortBy=publishedAt&apiKey=${apiKEY}`;
    let items = [];
	const fetchData = async () => {

    
    	const response = await fetch(dataUrl);
    	const data = await response.json();
		console.log(data);
    	items = data["articles"];
    };
    
	onMount(fetchData());
</script>
```

Next, add the following markup just below the closing `</script>` tag:

```html
<h1>
Daily News
</h1>

<div class="container">

		{#each items as item}
			<div class="card">
				<img src="{item.urlToImage}">
				<div class="card-body">
					<h3>{item.title}</h3>
					<p> {item.description} </p>
					<a href="{item.url}">Read</a>
				</div>
			</div>
		{/each}

</div>
```

Finally, add the styles below:

```html
<style>
h1 {
	color: purple;
	font-family: 'kalam';
}
.container {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
	grid-gap: 15px;
}
.container > .card img {
	max-width: 100%;
}
</style>
```

In both React and Svelte, we declared the `apiKEY` and `dataUrl` variables for holding the API key and the URL of our API.

Next, in React we created an `items` state variable using the `useState` hook but in Svelte we simply defined the state variable using the typical JS `let` keyword because in Svelte, variables are reactive state by default. 

In both libraries, when state changes, the component will re-render itself - except that in Svelte we don't need to use any special method to create reactive state.

Next, in both examples, we defined an async `fetchData()` method which simply invokes the JavaScript Fetch API to fetch data from the third-party endpoint. When we receive that, in React, we needed to use the `setItems()` method returned from the `useState()` hook to assign the data to the `items` array. But in the case of Svelte, we simply used the assignment operator in JavaScript.

Next, In React we used the `useEffect()` hook to call our `fetchData()` method which is used to perform any side effects in our components. Equivalently, we used the `onMount()` life-cycle method in Svelte to call the method when the component is mounted.  

Next, we displayed the data in React using the built-in JS `map()` method inside the [JSX](https://reactjs.org/docs/introducing-jsx.html) syntax which is a syntax extension to JavaScript used to describe the UI in React. 

This is how React allows you to use the display markup written in HTML inside the same JS file holding the component code. 

In Svelte, we use the same file but the HTML code and JS code are more separate and we can also access the variables defined in the JS code inside the HTML code.   

We use the `each` block to iterate over a list/array of data in Svelte.

You can learn about everything that Svelte can do on [the official docs](https://svelte.dev/docs).

## Step 5: Building Both Apps for Production

You can build your React and Svelte apps for production with easy steps. 

Simply go to your terminal and run the following command for React:

```bash
npm run build
```

This will create a `build` folder with static content that you can host in your server.

Next, run the same command in your Svelte app which will create a `public/build` folder with your static files.

And that's it! We've just created the same Web App with React and Svelte.

## Conclusion

We have seen that both React and Svelte use the concept of components with state, life-cycle methods and props but in slightly different ways. And both libraries provide useful tools to quickly scaffold and work with projects.

However, keep in mind that behind the scenes they use different approaches - Svelte is actually a build-time compiler while React is a library and run-time that makes use of a virtual DOM.

---

Regardless of the library/framework you're using to develop web apps, don't forget that you should **always** protect their source code when you're building enterprise or commercial apps. Check <a href="https://blog.jscrambler.com/protecting-your-react-js-source-code-with-jscrambler/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react">our guide</a> for protecting React apps and our tutorial [how to use the CLI](https://blog.jscrambler.com/jscrambler-101-how-to-use-the-cli/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react) to integrate Jscrambler. 

Originally published on the [Jscrambler Blog](https://blog.jscrambler.com/svelte-vs-react-differences-when-building-the-same-web-app/?utm_source=dev.to&utm_medium=referral&utm_campaign=svelte-vs-react) by Ahmed Bouchefra.