Avatar of Michael Thomas

Michael Thomas

Apr 10, 2023

Svelte - The Perfect State Management

I have tried many frameworks in the past but none accomplished state management in such an efficient and simple way as Svelte has.

Post Image

In the world of JavaScript frameworks, Svelte may be a newcomer compared to React, Angular(JS), and Vue. However, since its introduction in 2016, Svelte has made significant strides in implementing developer-friendly features that speed up project development.

Command - Svelte Project Quick Setup

npm create vite@latest my-svelte-project -- --template svelte

One of my favorite features of Svelte is its state management capabilities. If you've used React, you're probably familiar with the hoops you need to jump through to create a variable that updates in the DOM, the following code should look familiar.

React - State Management Example

import { useState } from 'react'; const [txt, setTxt] = useState('Hello World!); function UpdateTxt() { setTxt('hello world!'); }

The [object Object] function in React is asynchronous, which can cause issues when using the variable in other functions. Similarly, Vue and Angular have their own subpar state management solutions.

Vue - State Management Example

import {ref} from 'vue'; export default { setup() { return { txt: ref('Hello World!') } } } function UpdateTxt() { txt = 'hello world!'; }

In contrast, Svelte's state management solution is outstanding.

Svelte - State Management Example

let txt = "Hello World!"; function UpdateTxt() { txt = 'hello world!'; }

If you've never used Svelte before, you might be surprised at how straightforward it is to use. There are no imports, external libraries, or boilerplate code required – just initialize and update the state as needed with minimal code.

TLDR: Svelte makes state management simple and efficient, allowing developers to quickly build high-quality web applications.

Notes: This post only covers Svelte's local state management, ff you're interested in global state management, check out LogRocket's excellent post on the topic here.

TechBites