DEV Community

Fersho Pls
Fersho Pls

Posted on

Svelte beats react: faster, simpler, and better for your next web app!

Svelte is a relatively new JavaScript framework, but it has gained popularity for its simplicity and performance. Many people believe that Svelte is better than React for several reasons:

Svelte is faster than React. Svelte compiles your app's code at build time, which means that your app will run faster and use less memory at runtime. This can result in a better user experience and improved performance.

1. Svelte is easier to learn than React.

Svelte has a simpler and more intuitive syntax, which makes it easier for developers to pick up and start using. This can save time and effort when building apps with Svelte.

2. Svelte is smaller than React.

Svelte has a smaller codebase and produces smaller bundle sizes, which means that your app will be faster to download and use less storage on the user's device. This can be especially important for mobile apps.

3. Svelte has better developer tools than React.

Svelte includes a time-traveling debugger and other helpful features that make it easier for developers to find and fix bugs in their code. This can save time and improve the overall development experience.

All of these benefits make Svelte a compelling choice for building web applications. So if you're looking for a faster, simpler, and better framework for your next web app, consider giving Svelte a try.

See by yourself

Here is an example of how a simple counter component might be implemented in React and Svelte:

1. Creating a Counter

In react:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

in svelte:

<script>
  let count = 0;
</script>

<p>{count}</p>
<button on:click={() => count++}>Increment</button>
<button on:click={() => count--}>Decrement</button>
Enter fullscreen mode Exit fullscreen mode

2. Creating a TODO list

Here is an example of how a simple todo list component might be implemented in React and Svelte:

React:

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');

  function handleAddTodo() {
    setTodos([...todos, newTodo]);
    setNewTodo('');
  }

  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <input value={newTodo} onChange={(event) => setNewTodo(event.target.value)} />
      <button onClick={handleAddTodo}>Add Todo</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Svelte:

<script>
  let todos = [];
  let newTodo = '';

  function handleAddTodo() {
    todos = [...todos, newTodo];
    newTodo = '';
  }
</script>

<ul>
  {#each todos as todo}
    <li>{todo}</li>
  {/each}
</ul>
<input bind:value={newTodo} />
<button on:click={handleAddTodo}>Add Todo</button>
Enter fullscreen mode Exit fullscreen mode

3. Complex component: Login Form

Here is an example of how a more complex component, such as a login form, might be implemented in React and Svelte:

React:

import React, { useState } from 'react';
import axios from 'axios';

function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(event) {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await axios.post('/login', { username, password });
      const user = response.data;
      // Save user to local storage, etc.
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Username:
        <input value={username} onChange={(event) => setUsername(event.target.value)} />
      </label>
      <label>
        Password:
        <input value={password} onChange={(event) => setPassword(event.target.value)} type="password" />
      </label>
      {error && <p>{error}</p>}
      <button disabled={loading}>Login</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Svelte:

<script>
  import { post } from 'axios';

  let username = '';
  let password = '';
  let error = null;
  let loading = false;

  async function handleSubmit(event) {
    event.preventDefault();
    loading = true;

    try {
      const { data: user } = await post('/login', { username, password });
      // Save user to local storage, etc.
    } catch (err) {
      error = err.message;
    } finally {
      loading = false;
    }
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <label>
    Username:
    <input bind:value={username} />
  </label>
  <label>
    Password:
    <input bind:value={password} type="password" />
  </label>
  {#if error}
    <p>{error}</p>
  {/if}
  <button disabled={loading}>Login</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, Svelte is a powerful and efficient JavaScript framework for building web applications. Its unique approach to handling state and rendering components allows it to offer several advantages over frameworks like React, including better performance, simplicity, and developer tools. Whether you're a seasoned web developer or just getting started, Svelte is worth considering for your next project. Thank you for reading.

Top comments (5)

Collapse
 
moutafatin1 profile image
moutafatin1

In the end, I always come back to react, I prefer to write javascript than another weird syntax

Collapse
 
devdufutur profile image
Rudy Nappée

Can't agree more ! Immutability enforced, FP proof, pure JavaScript constructs...

Collapse
 
jackmellis profile image
Jack

I've spent a long time writing React and Vue. Vue actually offers similar let counter = 0 syntax now, but after the novelty wears off, I quickly find myself getting caught out by "magic", where what you write (assigning a value to a regular variable) completely obfuscates whats happening (state management + invalidation logic + rerender logic)
At least with react you are wholly explicit about your state updates.

...Also I just can't get on board with the {#each } syntax...

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

I recently came across Svelte, and it just amazes me how a NYT designer single-handedly was able to take the title from Meta's engineers; well, not really, but kind of, know what I am saying? One thing that I still use React is productivity and the humongus community built around it. I don't really care that much about performance for the time being. React FTW.

Collapse
 
jtlapp profile image
Joe Lapp

I used Svelte for a year and for the most part found it pretty simple, but every once in a while there were weird state updating issues. I found myself having to write unintuitive code for managing state by fooling Svelte's implicit rules into doing what needed to be done. I'm now learning REACT and can't yet say how it compares, but I am feeling happier about having more explicit control over state.