How is Svelte different than React?
Tags: javascript, svelte
Published: 2021-03-05 02:41:00

---
title: How is Svelte different than React?
published: true
description: How Svelte makes state management easier
tags: javascript, svelte
//cover_image: https://direct_url_to_image.jpg
---

To get a better understanding of what Svelte brings us, it helps to step back and look at how we got here:

Back in the 90s, in the original version of the web, there was only HTML. Browsers displayed static documents without any interactivity. The only way to get updated information, was by reloading the page, or navigating to a new page.

## Netscape and Internet Explorer

In 1995, [Netscape released JavaScript](https://en.wikipedia.org/wiki/JavaScript#History), making it possible to execute code on the end-user's machine. 

Now we could do things like: 

- Read a value from the DOM
 `document.getElementById(...).innerText`
- Write a value to the DOM: `document.getElemetById(...).innerText = ...`
- Get notified when something happens: `<button onclick="alert(1995)">`.

As developers began experimenting with this newfangled JavaScript thing, they found one aspect really tough: dealing with the differences between browsers. Both Netscape Navigator and Internet Explorer did things in their own way, making developers' responsible for handling those inconsistencies.

The result was code like:

```javascript
var isNetscape, isIE

// figure out which browser this is
if (parseInt(navigator.appVersion) >= 4) {
  isNetscape = (navigator.appName == "Netscape");
  isIE = (navigator.appName.indexOf("Microsoft") != -1);
}

// branch based on browser type
if (isIE) {
  // The Internet Explorer Way™
} else if (isNetscape)
  // The Netscape Way™
}
```

This kind of browser detection code littered codebases everywhere. The extra branching was a nuisance, like a cognitive tax, making code harder to read and maintain. Translation: not fun.

## jQuery

In 2006, John Resig released a compatibility layer called [jQuery](https://en.wikipedia.org/wiki/JQuery#History). It was a way to interact with the DOM without being an expert on browser feature matrices. It completely solved the inconsistency issue. No more `if (isNetscape)` or `if (isIE)` conditions!

Instead, we could interact with the page using CSS selectors, and jQuery dealt with the browser on our behalf.

It looked like this:

```javascript
// read state
$('form input#email').val()

// write state
$('h1').text('Hello World!')

// get notified when something changes
$('button').on('click', function() {
  alert(2006)
})
```

But there were some challenges here too:

1. **Selectors**: If the structure of the markup changed - which happens a lot - it can break the CSS selector. For example, if you had a selector `$('h1')..`, then you change the markup from `<h1>` to an `<h2>`, your selector just silently stops working, and you won't know until a user complains. 
2. **Syncing state**: State changes happen in 2 directions, DOM-to-model and model-to-DOM. jQuery didn't provide any tooling here, leaving developers responsible for managing the synchronization logic on their own.  

## AngularJS

In 2010, Google launched [AngularJS 1.x](https://en.wikipedia.org/wiki/AngularJS), a framework that helps with state management.

Instead of writing jQuery code, like:

```html
<script>
  $('h1').text(someExpression)
</script>
<h1>
```

Expressions (called bindings) could be embedded directly inside the HTML:

```html
<h1>{{someExpression}}<h1>
```

and Angular would sync those bindings for us.

Later, if we change our HTML, say by switching an `<h1>` to an `<h2>`, nothing breaks with the Angular version. There's no CSS selectors to update.

AngularJS components looked like this:

```html
<!-- specify where our controller/component mounts to -->
<div ng-app="myApp" ng-controller="myCtrl">
  <!-- binding to a variable -->
  <h1>{{year}}</h1>
</div>

<script>
// declare a module
var app = angular.module('myApp', []);

// declare a controller
app.controller('myCtrl', function($scope) {
  // update a variable and trigger syncing
  $scope.year = 2010;
});
</script>
```

The magic was that anytime you changed something on the `$scope` variable, Angular would go thru a "digestion cycle", that recursively updated all the bindings.

But there were some problems here too:

- **It only worked in the browser**: If a search engine crawled the page, it would see ```<h1>{{someExpression}}</h1>```. Unless you're trying to rank high for ```{{someExpression}}```, that's not great.

- **The digestion loop was inefficient**: It takes time to walk the DOM tree and apply changes. Sometimes it could take multiple passes for all the values to settle.

## React

In 2013, Facebook [launched React](https://en.wikipedia.org/wiki/React_(JavaScript_library)#History), a library for syncing state with UI.

It solved some issues that AngularJS 1.x had. It's isomorphic, it can render HTML both on the server and in the browser, fixing the SEO problem. It also implemented a more efficient syncing algorithm called [Virtual DOM](https://reactjs.org/docs/faq-internals.html).

Refresher: Virtual DOM keeps a copy of the DOM in memory. It uses the copy to figure out what changes (the delta), while limiting potentially slow interactions with the browser DOM. (Though it's been pointed out that [this may be overhead](https://svelte.dev/blog/virtual-dom-is-pure-overhead).)

It's still conceptually similar to AngularJS, from a state management perspective. React's `setState({value})` or in more recently, the `useState()` hook, is roughly equivalent to Angular's `$scope.value = value`.

Hook example:

```javascript
// React state with hooks
const [year, setYear] = useState(null)

// setting state
// functionally equivalent to AngularJS's
// `$scope.year = 2017`
setYear(2017)
```

### The problem

React relies on developers to signal when things change. That  means writing lots of Hook code. But Hooks aren't trivial to write, they come with a bunch of [rules](https://reactjs.org/docs/hooks-rules.html), and those rules introduce a [extra cognitive load into our codebases](https://github.com/joshnuss/react-hooks-in-svelte).

## Svelte

In 2019, [Rich Harris](https://github.com/Rich-Harris) released Svelte3. The idea behind Svelte is: 

**What if a compiler could determine when state changes?**
That could save developers a lot of time.

It turns out to be a **really good idea**. Being a compiler, Svelte can find all the places where our code changes state, and update the UI for us.

### Example

Say we assign a variable inside a Svelte component:

```html
<!-- a .svelte component -->
<script>
// assign a value
let year = 2019
</script>

<!-- this <h1> depends on `year` state -->
<h1>Hello {year}!</h1>
```

Svelte detects the `let` statement and starts tracking the variable. If we change it later, say `year = 2021`, Svelte sees the assignment `=` as a state change and updates all the places in the UI that depend on that binding. 

Svelte is writing all the Hooks code for us! 

# Conclusion

If you think about it, a big part of a developer's job is organizing state, moving state back and forth between the UI and the model. It takes effort, and it's tricky to get right. By offloading some of that work to compile-time tools, we can **save a lot of time and energy**.

Another side effect is, we end up with **less code**. That makes our programs smaller, clearer to read, **easier to maintain**, cheaper to build, and most importantly: **more fun** to work with.

# Want more?

If you'd like to learn more about Svelte, check out my [short video courses](https://joshuanussbaum.podia.com) ✨