Files
learning-log/concepts/03-react-vs-svelte.md
2026-01-10 21:18:01 +01:00

71 lines
2.3 KiB
Markdown

# 2025-12-22
Today we are playing around with Svelte and React.
Comparing the runtime and performance.
React and Svelte are both JavaScript frontend-frameworks for building user interfaces. Although they do the same things, they do things very differently.
React uses the Virtual DOM to update the UI. The Virtual DOM is something that React creates and compares to the real DOM. It then changes the real DOM based on the differences it found.
This approach takes some extra computing/browser power because it causes a lot of renders of the DOM.
This is not necessarily a bad thing, because the React framework is optimized to do it and can handle complex UIs very well.
Svelte is a little bit different. Svelte is a compiler that compiles your code to optimized JavaScript at build time. This means that there is no Virtual DOM and no extra renders. All functions and logic in the script tags are compiled to be optimized JavaScript that directly manipulates the DOM. Just like Vanilla JavaScript. This makes Svelte faster, causes fewer renders, and uses less browser power.
This is especially beneficial for smaller applications or applications that need to run on low-power devices.
But bigger applications can become a bit more complex to manage because of the lack of a Virtual DOM and the management of state can become tricky.
One isn't better that the other, but it is good to know the differences and knowing that there are multiple ways to achieve the same goal.
Know when to use the right framework.
This is an example of Svelte code.
```svelte
<script>
console.log("Svelte Script Ran");
// Standard Variables
let count = 0;
// Reactive Declarations
$: doubleCount = count * 2;
const increment = () => {
count += 1;
};
</script>
<div>
count is {count}
Double count is {doubleCount}
<button onclick={increment}> Count </button>
</div>
```
This is an example of React code.
```jsx
import React from "react";
import "./App.css";
function App() {
const [count, setCount] = React.useState(0);
//Derived Variable
const doubleCount = count * 2;
console.log("App Rendered");
return (
<>
<div>
<h1>React Double Count</h1>
<p>Count: {count}</p>
<p>Double Count: {doubleCount}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
</div>
</>
);
}
export default App;
```