Choosing between React and Svelte
Over the past few years, there has been a constant explosion of new JavaScript libraries and frameworks - all promising to solve the complexities of building fast and efficient user interfaces (UIs) while maintaining a relatively smaller package size and improving performance.
The constant emergence of new JavaScript frameworks and libraries creates the never-ending tussle of the best library or framework to build UIs among developers and software engineers.
These libraries and frameworks include but are not limited to React, VueJS, Angular, Svelte, Nue, Ember, and many more.
In this article, I will compare Svelte vs. React, I will take a look at what Svelte is used for, and how the Svelte framework compares with React. I will answer questions such as:
- Why is Svelte so good?
- What makes Svelte different?
- Should you start using Svelte?
- Who uses Svelte?
- and many more.
Let's dive right in! 🚀
What is React?
The React library is a declarative, flexible, and open-source JavaScript library developed by Facebook. It is primarily used for building interactive user interfaces based on UI components for web applications quickly and efficiently with remarkably less code than you would with vanilla JavaScript.
Key features of React
React has gained popularity among the developer ecosystem and many organizations because of so many features such as its simplicity, easy learning curve, and many more. React has been the most used JavaScript library since 2016, according to The State of JS 2022, whereas it emerged as the most used JavaScript library in 2023 according to a report by Statista.com.
Some of the great features that come out of the box with React are:
React Performance
One of the key features that sets React apart from other libraries is performance. This is because React does not manipulate the DOM (Document Object Model) directly, instead, it interacts with what is known as the virtual DOM. It does this by creating virtual components that will be converted into the DOM, resulting in smoother and faster performance.
Virtual DOM
The virtual DOM is also a standout feature of React that accelerates the application development process while ensuring flexibility. DOM is at the heart of web development. With React's Virtual DOM, a web page is mirrored in the virtual memory, enabling a more efficient approach to updating the UI.
In this mechanism, a virtual DOM object mirrors the original DOM. It functions like one-way data binding. Whenever changes are made within the web application, the entire UI is re-rendered within the virtual DOM representation. What sets it apart is that it subsequently compares the old DOM representation with the new one. Only the elements that have changed are updated in the real DOM in what is known as reconciliation, significantly reducing unnecessary updates and enhancing performance.
One-way data binding
One-way data binding is a core feature of React, characterized by its unidirectional data flow. In React, you are compelled to adhere to this data flow model, which requires updating the state from a higher level in the component (e.g. a state value in the component or higher up in the component tree), which gets passed down into the components' rendered output. This approach ensures a clear and predictable flow of data, promoting application stability and maintainability.
Here's a simplified example to illustrate how one-way data binding works in React:
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
// This is a callback function to update the count state
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
<h1>One-Way Data Binding in React</h1>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}
export default App;
In this example above ⬆
- We import React and
useState
from the React package.
- We define a functional component
App
that represents our application.
- Inside the component, we use the
useState
hook to create a state variable called
count
and a function called
setCount
to update it.
- We define a callback function
handleIncrement
, which uses
setCount
to update the
count
state. We only update the state by invokingsetCount
, ensuring one-way data binding.
- In the JSX, we display the current
count
value using curly braces
{count}
and bind the
handleIncrement
function to a button's
onClick
event.
When the "Increment" button is clicked, it invokes the handleIncrement
function, which, in turn, updates the
count
state using the
setCount
function. This change in state triggers a re-render, and the updated
count
value is reflected in the UI.
This is an example of one-way data binding, as data flows from the component's state to the UI, and any updates to the data are managed through callback functions.
JSX (JavaScript Syntax Extension)
JSX, short for JavaScript Syntax Extension, is a foundational feature of React that simplifies the process of creating user interfaces within applications. This markup syntax closely resembles HTML, making it exceptionally user-friendly for developers. With JSX, you can craft React components using a syntax that feels familiar and intuitive, similar to writing HTML.
JSX code is subsequently transpiled into JavaScript calls for execution within React. React utilizes a preprocessor called Babel for code transpilation.
React components
React's architectural superiority lies in its use of components as the fundamental building blocks for developing applications. These components are likened to independent Lego bricks that, when assembled, constitute the entire UI of your application.
In React, everything is structured as a component, fostering modularity and reusability in web interface and application development. By breaking down the UI into distinct components, React simplifies code maintenance, especially in the context of larger and more complex projects.
What is Svelte?
Svelte is an open-source modern web framework for building web applications. It was developed by Rich Harris and maintained by members of the Svelte core team. It ranks as the most admired and most loved JavaScript web framework in 2022 on the Stack Overflow Developer Survey.
Key features of Svelte
The Svelte UI framework has distinguished itself from the rest of JavaScript frameworks/libraries in that it lets you build what you want without making use of a virtual DOM which introduced some performance limitations like increased memory usage due to constant element comparisons for updates.
Svelte is easier to write and learn. Its app framework, SvelteKit, makes it easier to build Jamstack web applications. It offers server-side rendering, components, scoped CSS, file-system-based routing, code-splitting, and many more features.
Let’s explore some of the features of Svelte:
Svelte reactivity
Reactivity means automatic updates of changed values to the DOM.
Svelte brings reactivity to application development by offering a straightforward and highly efficient approach. When you want your DOM values updated and recalculated based on other variables, you can achieve this with responsive statements.
Simply prefix the variable you wish to make reactive with a dollar sign followed by a colon ($:)
, and you are good to go.
This code below demonstrates reactivity in Svelte. ⬇
<script>
let text = "";
$: characters = text.length;
$: words = text.split(" ").length;
$: console.log("your text:", text);
</script>
<style>
body {
padding: 0;
margin: 0;
background-color: aliceblue;
}
textarea {
width: 100%;
background: #fff;
font-size: 2rem;
}
p {
color: #666;
font-weight: 700;
}
</style>
<div>
<textarea bind:value={text} rows="5" />
<p>Character Count: {characters}</p>
<p>Word Count: {words}</p>
</div>
What sets Svelte apart is its "truly reactive" nature. Unlike other frameworks like React which rely on hooks to manage state updates, Svelte surgically updates the DOM at build-time. This approach minimizes unnecessary overhead and simplifies the development process.
Learn more about Svelte reactivity on the Svelte Society website.
Less code in Svelte (sometimes 😉)
As developers, we often strive for code that is not only functional but also concise and easy to maintain. Svelte's "Less Code" feature embodies this principle, emphasizing the importance of writing minimal code for maximum impact. By reducing the lines of code we write, we save time, minimize the risk of bugs, and enhance code readability. Svelte accomplishes this by introducing a straightforward format, often written in TypeScript - a superset of JavaScript, that simplifies the development process.
For smaller apps, this streamlined approach can significantly reduce the code size compared to equivalent implementations in React or Vue, which can be up to 30-40% larger.
However, it’s worth noting that once Svelte apps reach a certain size, they will end up outputting larger JavaScript bundles than React, as shown in this study. It is unlikely your app will reach that size, luckily.
No virtual DOM
While React and Vue use a virtual DOM to manage state updates and improve web apps, Svelte uses a more efficient and developer-friendly approach. To run your code in Svelte, there is no need to load a full library into the browser. To render your app, a basic .js file is loaded onto the page.
All object modifications are handled at compile time, avoiding the overhead associated with a virtual DOM. This not only improves efficiency but also considerably reduces file size, which is especially beneficial for mobile devices.
Svelte compiles your code into lean vanilla JavaScript, as opposed to React and Vue, which use a virtual DOM to manage web page updates, resulting in a speedier app from the start. This not only makes your program lighter but also makes it more user-friendly.
First time here? Discover what Prismic can do!
👋 Meet Prismic, your solution for creating performant websites! Developers, build with your preferred tech stack and deliver a visual page builder to marketers so they can quickly create on-brand pages independently!
Differences between Svelte and React: a head-to-head comparison
In this section, we will look at the key differences between React and Svelte and make some comparisons.
- Installation and Scaffolding: React and Svelte offer straightforward installation and scaffolding processes, but React's ecosystem provides more boilerplate and configuration options compared to Svelte's simplicity.
- To install React and bootstrap a quick React project called
new-react-project
, run the following command:
npx create-next-app@latest new-react-project
cd new-react-project
npm run dev
To install Svelte and bootstrap a quick Svelte project called new-svelte-project
, run the following command in your terminal:
npm create svelte@latest new-svelte-project
cd new-svelte-project
npm install
npm run dev
- Differences: React utilizes a virtual DOM for optimizing updates, while Svelte compiles away the virtual DOM in favor of lean code. Both have advantages depending on the use case.
- Component Organization: React and Svelte both enable excellent component organization, with React offering a more extensive ecosystem of tools.
- Performance: Svelte directly manipulates the DOM on state changes, while React's virtual DOM incurs some overhead. Both offer great performance that continues to improve.
- Documentation: Both provide excellent documentation. React boasts extensive documentation and resources, while Svelte's documentation is very concise.
- Community: React has a large, well-established community, while Svelte's community is smaller but steadily growing.
- Learning Curve: Svelte has a slightly gentler learning curve thanks to its reactivity and simplified syntax. React's ecosystem breadth rewards time invested.
- State Management: React offers robust built-in state management, while Svelte simplifies it through reactivity. Both enable effective state handling.
- Developer Experience: React and Svelte aim to optimize DX - React through a mature and versatile ecosystem and Svelte through conciseness. Preferences vary.
- Tooling and Ecosystem: React has an extensive tooling ecosystem, while Svelte's tooling is growing but efficient for smaller projects.
- Syntax: Svelte simplifies syntax, resembling HTML, while React uses JSX and CSS-in-JS to create the simplest of interfaces.
- Bundle Size: In most cases, Svelte generates smaller JavaScript bundles than React thanks to Svelte’s compiler.
- Code Maintainability: Svelte emphasizes conciseness with its "less code" philosophy, while React offers many architectural options. Both aid maintainability.
- Testing: React has very extensive testing support. Svelte simplifies writing testable code. Both enable robust testing.
Svelte vs React feature comparison table
Virtual DOM, efficient
No Virtual DOM, fast
Mature, vast ecosystem
Less code, reactivity
Jordan Walke
Rich Harris
2011
2016
High
High
Active community
Growing community
Extensive
Simpler
Built-in, complex
Lightweight, reactivity
Reactive, flexible
Reactive, less code
Component-based
Component-based
Extensive
Growing, efficient
Large developer resources available
Growing developer resources
Who uses React?
React is used by big companies and even startups for their web applications. There are about 8, 000+ companies relying on React for their web applications. These companies include Facebook (Meta), Instagram, Salesforce, Tesla, PayPal, Netflix, Walmart, Uber, Shopify, etc., to mention but a few.
Who uses Svelte?
Svelte is trusted by large entities like the New York Times for their applications. This is because Svelte emerges as the hero we've all been waiting for. It's a groundbreaking framework that handles the heavy lifting for developers by embracing reactivity and shifting computation into a compilation step, resulting in lightning-fast, high-performance, vanilla JavaScript.
Some of these companies who trust Svelte in their production environment include:
Yahoo! Inc., Array, Cloudflare, Spotify, Apple Music, Yelp, NBA, Square, Brave, IKEA, Decathlon, etc.
Svelte vs. React - the creator of Svelte weighs in
You’re starting a new web project and you’re hesitating between Svelte and React? We've got you covered! Watch as Rich Harris, the creator of Svelte, provides a full evaluation of those options.
Spoiler: Rich knows more about React than you might imagine 🤯
Making your decision between Svelte and React
In deciding between React and Svelte for 2024, several crucial factors come into play. React is a library known for its extensive ecosystem and robust tooling, making it a powerful choice for large-scale applications, especially when you require a mature, feature-rich framework. Its virtual DOM approach provides efficient DOM manipulation, ensuring smooth updates for complex user interfaces.
Svelte, on the other hand, is a compiler, offering a leaner codebase with a no-virtual-DOM philosophy. This method results in faster development and smaller bundle sizes, making it ideal for projects prioritizing performance and code maintainability.
The decision depends on your project’s specific requirements. React finds usefulness for diverse application types, including video streaming platforms, social media platforms, and e-commerce sites. At the same time, Svelte, with its ease of learning and efficient code, excels in scenarios where performance, speed, and maintainability are paramount, making it a great choice for JAMstack sites and building dashboards.
Over the past few years, I have used React to build complex web applications such as custom CMS, SPAs, and custom E-commerce applications, among others whereas on the other hand, I have used Svelte to build simple SPAs. I have enjoyed using both tools for my development works so far.
React vs. Svelte: Who wins?
When deciding between React and Svelte for your project, it is essential to consider your application's specific goals and requirements. Both frameworks have their unique strengths and weaknesses, as highlighted above. Your choice ultimately depends on what you prioritize and aim to achieve with your development work.
React offers a vast ecosystem of tools and libraries, making it ideal for large-scale, complex projects that require a mature and versatile framework.
On the other hand, Svelte has gained popularity for its simplicity, efficient performance, and smaller bundle sizes. It excels in smaller to medium-sized projects, where speed and a minimal code footprint are important.
Wrapping up
In this article, you have learned about the comparative differences between the React library and Svelte compiler such are performance differences, and use and non-usage of virtual DOM, React makes use of syntactic sugar syntax called JSX, which is HTML-like syntax, whereas Svelte makes use of plain HTML, CSS, and JavaScript.
In the ongoing tussle between React and Svelte, the choice ultimately hinges on your project's specific needs.
React, known for its extensive ecosystem and suitability for large-scale, complex projects, excels in providing a mature and versatile framework. On the other hand, Svelte's growing popularity arises from its simplicity, efficient performance, and minimal code footprint, making it an excellent choice for smaller to medium-sized projects prioritizing speed.
I hope that this article will help you make an informed decision about what library or framework to go for on your next web application project.
Further readings
- Why Svelte is the Next Big Thing in JavaScript Development
- What are the features of React?
- SvelteKit Tutorial: Build a Website From Scratch
Helpful resources
To dig deeper into SvelteKit, have a look at the official documentation for building a website with Prismic and Svelte and these handy resources: