From React to Svelte: Exploring Basic Concepts and Comparisons š§āš³š¤.
Introduction:
As web developers, we are always on the lookout for frameworks that can enhance our productivity and deliver exceptional user experiences. React has been a go-to choice for many, but recently, Svelte has gained attention for its simplicity and performance-driven approach. In this article, weāll delve into the basic concepts of both React and Svelte and provide code snippets for comparison, enabling you to make an informed decision about which framework suits your development needs.
Svelte has also being doing great rising up the popularity chart as most react developers do want to have a taste of it and some do stay.
Hopefully in this article weāll get deeply into what to expect transitioning into svelte as a react developer.
Prerequisites:
To follow along with the examples in this article, you should have a basic understanding of JavaScript and familiarity with front-end web development concepts.
Letās take a look at some basic comparisons with concepts we have been familiar with in react and how it looks like in svelte.
Component-Based Architecture:
React:
In React, building reusable components is a fundamental concept. Components encapsulate their own state, props, and render functions. Hereās an example of a basic functional component in React:
import React from 'react';
const MyComponent = ({ name }) => {
return <div>Hello, {name}!</div>;
};
export default MyComponent;
Svelte:
Svelte takes a similar component-based approach, but with a more streamlined syntax. Hereās the equivalent Svelte component:
<script>
let name = 'John';
</script>
<div>Hello, {name}!</div>
State Management:
React:
React provides the useState hook for managing state within functional components. Hereās an example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;
Svelte:
In Svelte, state management is built-in and declarative. Hereās an equivalent Svelte component using reactive statements:
<script>
let count = 0;
const increment = () => {
count += 1;
};
</script>
<div>
<p>Count: {count}</p>
<button on:click={increment}>Increment</button>
</div>
Conditional Rendering:
React:
React allows conditional rendering using JavaScript expressions. Hereās an example:
import React from 'react';
const Greeting = ({ isLoggedIn }) => {
return (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);
};
export default Greeting;
Svelte:
Svelte uses reactive statements for conditional rendering. Hereās an equivalent Svelte component:
<script>
let isLoggedIn = true;
</script>
<div>
{#if isLoggedIn}
<p>Welcome back!</p>
{:else}
<p>Please log in.</p>
{/if}
</div>
Lifecycle Methods:
React:
React provides lifecycle methods that allow you to perform actions at different stages of a componentās lifecycle. For example, the componentDidMount method is invoked after the component is rendered for the first time. Hereās an example:
import React, { Component } from 'react';
class MyComponent extends Component {
componentDidMount() {
console.log('Component has mounted');
}
render() {
return <div>Hello, World!</div>;
}
}
export default MyComponent;
Svelte:
In Svelte, you can use lifecycle functions to achieve similar functionality. For example, onMount is invoked when the component is first rendered. Hereās an equivalent Svelte component:
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('Component has mounted');
});
</script>
<div>Hello, World!</div>
Event Handling:
React:
React uses synthetic events and event handlers to handle user interactions. Hereās an example of handling a button click event:
import React from 'react';
const Button = () => {
const handleClick = () => {
console.log('Button clicked');
};
return <button onClick={handleClick}>Click me</button>;
};
export default Button;
Svelte:
Svelte simplifies event handling by using on:event directives. Hereās the equivalent Svelte code:
<script>
let count = 0;
function handleClick() {
count += 1;
}
</script>
<main>
<h1>Counter: {count}</h1>
<button on:click={handleClick}>Increment</button>
</main>
CSS Styling:
React:
In React, you can style components using CSS classes or inline styles. Hereās an example using CSS classes:
import React from 'react';
import './Button.css';
const Button = () => {
return <button className="button">Click me</button>;
};
export default Button;
Svelte:
Svelte provides CSS inside aĀ <style>Ā block will be scoped to that component.
This works by adding a class to affected elements, which is based on a hash of the component styles (e.g.Ā svelte-123xyz)
<style>
p {
/* this will only affect <p> elements in this component */
color: burlywood;
}
</style>
To apply styles to a selector globally, use theĀ :global(...) modifier.
<style>
:global(body) {
/* this will apply to <body> */
margin: 0;
}
div :global(strong) {
/* this will apply to all <strong> elements, in any
component, that are inside <div> elements belonging
to this component */
color: goldenrod;
}
p:global(.red) {
/* this will apply to all <p> elements belonging to this
component with a class of red, even if class="red" does
not initially appear in the markup, and is instead
added at runtime. This is useful when the class
of the element is dynamically applied, for instance
when updating the element's classList property directly. */
}
</style>
If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with -global-.
The -global- part will be removed when compiled, and the keyframe then be referenced using just my-animation-name elsewhere in your code.
<style>
@keyframes -global-my-animation-name {...}
</style>
There should only be 1 top-level <style> tag per component.
However, it is possible to have <style> tag nested inside other elements or logic blocks.
In that case, the <style> tag will be inserted as-is into the DOM, no scoping or processing will be done on the <style> tag.
<div>
<style>
/* this style tag will be inserted as-is */
div {
/* this will apply to all `<div>` elements in the DOM */
color: red;
}
</style>
</div>
Note that both React and Svelte offer various approaches to styling, including CSS-in-JS libraries or CSS preprocessors.
Conclusion:
React and Svelte are powerful frameworks that offer different approaches to building web applications. Reactās lifecycle methods, synthetic events, and flexible styling options provide a rich development experience. Svelte, on the other hand, simplifies development with reactive functions, event directives, and concise inline styling.
Remember to consider factors such as performance, learning curve, and ecosystem support when selecting the framework that best aligns with your development goals.
Happy coding chefs, get cooking š§āš³š¤.
If this article is informative drop a like and a comment.
Gracias š.
Reference:
https://svelte.dev/docs