Svelte and React are both used for Web development. React is a fantastic tool which has dominated the industry for a while now whereas Svelte is newer in the field and is gaining significant popularity.
Overview
When I first heard about Svelte I wanted to try it out and was surprised to see how less code you have to write to do the same amount of work in React.
Lets take a look at code below,
React
import { useState } from 'react';
const FormExample = () => {
const [name, setName] = useState();
const [age, setAge] = useState();
function handleNameChange(event) {
setName(event.target.value);
};
function handleAgeChange(event) {
setAge(event.target.value);
};
return (
<div>
<input type="text" value={name} onChange={handleNameChange} />
<input type="text" value={age} onChange={handleAgeChange} />
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
export default FormExample;
Svelte
<script>
let name = "";
let age = "";
</script>
<input type="text" bind:value={name}>
<input type="text" bind:value={age}>
<p>Name: {name}</p>
<p>Age: {age}</p>
You can clearly see how simple Svelte is.
Just from this example we can tell that React has a steep learning curve than Svelte.
Some of the learning curve of React includes:
- Concept of JSX and Virtual DOM.
- Different Hooks used for different purpose.
- Next.js for Server-side rendering (SSR).
- Handling bundle size as the app grows larger.
- Rapid upgrades to the ecosystem, difficult to keep up.
- Utilizing React Developer Tools for debugging.
- React Router for navigation.
On the other hand Svelte just uses plain Javascript, HTML and CSS. In addtion, it only introduces few new syntax making is easier to learn.
<script>
let count = 0;
$: timesTwo = count * 2;
function onClick() {
count += 1;
}
</script>
<button on:click={onClick}>Click me!</button>
<p>{count} x 2 = {timesTwo}</p>
<style>
p {
color: blue;
}
</style>
Bundle Size & Performance
Svelte app has lesser bundle size than for React app which also contributes to the faster app load and improved performance in the production.
The production built of the Svelte app is lighter and surgically updates the DOM without relying on any complex reconciliation techniques and use of Virtual DOM which adds more code to the bundle as in React.
Conclusion
React is still the most famous tool for web development. Svelte is comparatively new and gaining popularity due to its ease of use.
When taking about cross-platform flexibility, Svelte also has Svelte Native like the way React has React Native for mobile app development.