Getting Started with Svelte 5: A Guide for React Developers
- svelte
- •
- react
The Svelte team announced the release of version 5 on October 20, 2024 🎉🎉, bringing several exciting new features and enhancements for developers. This latest version continues to build on Svelte's reputation for simplicity and performance, making it even more appealing to modern web developers. In this guide, we'll cover the basics of Svelte 5 and help you understand how to transition smoothly from React.
What is Svelte(Kit)?
Svelte is yet another single-page application (SPA) framework in the growing landscape of JavaScript frameworks. Opsi No. Svelte is not a framework but a compiler. It compiles your component code for single-page applications (SPAs) at build time into highly optimized vanilla JavaScript, which is what runs in your browser. This means less runtime overhead and better performance out of the box.
SvelteKit extends Svelte by providing a complete toolkit for building web applications, including features like routing, server-side rendering (SSR), static site generation (SSG), and client-side rendering (CSR).
Why Should React Developers Care About Svelte?
SvelteKit is gaining popularity for its simplicity and performance. If you've worked with React, you've probably encountered situations where the overhead of managing state, using hooks, and dealing with performance bottlenecks became challenging. SvelteKit offers a lighter approach with fewer dependencies, faster builds, and a cleaner syntax. Svelte is based on HTML rather than JS.
Key Differences Between React and SvelteKit (Basics)
Simple Component
Svelte’s writing form is a little weird for React developers because there is no JSX or wrapped components.
React Example:
Note: Adding types to useState
and using useEffect
to double the value is not necessary in this case. We included them here simply to follow a common pattern in React.
Svelte Example:
Svelte's syntax is cleaner, and there's no need for hooks like useState
to manage component state. Instead, Svelte uses signals to create reactive state, allowing you to update the state effortlessly. You don’t need to import anything in SvelteKit; simply use $state
, and it magically handles reactivity for you.
Additionally, Svelte offers $derived
to create derived state that relies on other state variables. The expression inside $derived(...)
should not have side effects, and it will automatically re-run whenever any of the values it depends on change, making it easy to calculate new values based on the current state.
Side Effects
In Svelte 5, you can use $effect
and $effect.pre
to manage side effects in your components, which can be compared to React's useEffect
and useLayoutEffect
hooks.
Svelte $effect
and $effect.pre
$effect
runs after the component is mounted and whenever its dependencies (like $state
or $derived
) change. It executes after the DOM updates.
Example:
A cleanup function can be returned, executing before the next effect or on unmount.
Also to prevent something from being treated as an $effect
or $derived
dependency, you can use untrack
:
$effect.pre
runs before the component is mounted and whenever its dependencies change, executing right before the DOM updates.
Example:
Svelte automatically tracks dependencies, simplifying state management compared to React's useEffect
and useLayoutEffect
hooks. This built-in tracking also helps prevent common beginner mistakes that can lead to unexpected behavior, or as some say, "shooting yourself in the foot."
Loop
In Svelte, you can use the {#each}
block to create loops, which is concise and integrates seamlessly with the reactivity system:
Svelte automatically optimizes updates to the DOM, efficiently re-rendering only the elements that change.
In React, loops are typically implemented using the map()
method within JSX:
Unlike React, which requires a key
prop for each item to identify changes, additions, or removals—facilitating optimal reconciliation with the virtual DOM—Svelte handles updates automatically without the need for explicit keys.
React's useRef
and Svelte's Binding Mechanism
In React, the useRef
hook is commonly used to directly interact with DOM elements or to store mutable values without triggering re-renders. It allows you to maintain a reference to a DOM node and access it imperatively:
In Svelte, you can achieve similar functionality using the bind:this
directive:
you're not limited to just bind:this
for DOM elements. You can also use bind
for two-way binding of values, allowing you to synchronize state with input fields effortlessly. This binding allows you to directly connect a form input or other elements to a reactive variable without needing to manage refs explicitly:
Svelte's Special Elements:
Svelte have many useful special element.
<svelte:window>
This provides a unique syntax for adding event listeners to the window object using <svelte:window>
. This special element simplifies global event handling within your Svelte components.
Let's see an example how this is useful:
Lets Implement this same thing with React
React requires significantly more code to achieve the same functionality. Overall, Svelte's <svelte:window>
component offers a more streamlined and declarative approach for handling global events like scrolling, while React provides flexibility and control, albeit with additional complexity in setup.
<svelte:element>
In Svelte, you can use the <svelte:element>
tag to create dynamic elements. This allows you to specify which HTML element to render based on a variable or condition at runtime. Here's a simple example demonstrating how to use <svelte:element>
to create dynamic elements:
Here's a similar example in React:
In the React example you might encounter compiler errors or lose autocompletion when using dynamic elements this way, especially if the compiler cannot infer the element type. In contrast, SvelteKit handles dynamic elements seamlessly, providing zero issues with autocompletion and type inference.
Learn more about svelte's special elements: https://svelte.dev/docs/special-elements
Props
In Svelte, you can pass props directly to a component and access them using the $props
keyword.
In Svelte, passing props is quite similar to React, where the parent component sends data to the child component. However, I find Svelte's approach to be slightly better and more concise.
Todo App
Now Lets Make a simple todo app with Svelte and React
Svelte way
Now let's rebuild this with React
The Svelte approach in the example feels much closer to raw HTML and JavaScript, offering a better developer experience (in my opinion). Give it a try, and you might just fall in love with the simplicity and efficiency of creating modern web applications with Svelte!
I have just covered the basics; for more in-depth information, I recommend reading the SvelteKit documentation.
Conclusion
Svelte(Kit) offers React developers a fresh and efficient way to build modern web applications. Its simplicity, performance, and built-in features like SSR, SSG, and scoped styling make it an exciting alternative to React and Next.js. While the learning curve is gentle, SvelteKit's approach can lead to cleaner, faster, and more maintainable code.
If you’re a React developer looking to explore something new, give SvelteKit a try. Its simplicity and power may just win you over!