Blog

Global State Management in Svelte

Frontend

When we manage global states in frontend, for example, in React, we use React Hooks or Redux in most cases.
But the implementation of Rudux is complecated and redanduncy. Although React Hooks is somewhat better in that respect, I want to do that more easiliy!

I often used to use React on my personal project a few years ago. However, the global state management is very annoying for me and that's why I decided to change the framework from React to Svelte (Although, strictly speaking, Svelte isn't a framework, it's a compiler).

The management of global states in Svelte is much easier than that in React.
Let's explain in order.

0. Create Svelte project

npx degit sveltejs/template my-project
cd my-project
npm install
npm run dev

See the official page.

1. Create stores.js in src directory

First, in src directory, create a JavaScript file in which declares and stores global states.
The file name is arbitrary like stores.js or globalState.js, etc.

2. Declare global state variables using writable

// src/stores.js
import { writable } from 'svelte/store';

export const myName = writable("Adam");

By doint this, we can use this value(myName here) and change it anywhere/anytime in project.

3. Use global states

We can use global state values by adding prefix($) to them. For example, in Home.svelte:

// src/routes/Home.svelte
<script>
import { myName } from '../stores';
</script>

<span>My name is {$myName}.</span>

4. Update global states

It's also pretty easy to change states. All we have to do is import global states and assign new values to them. For example, in About.svetle:

// src/routes/About.svelte
<script>
import { onMount } from 'svelte';
import { myName } from '../stores';

onMount(async () => {
$myName = "Eve";
});
</script>

<span>My real name is {$myName}.</span>

5. Conclusion

Once experience this, it's simple and easy enough to hesitate to use other frontend frameworks.

It also works SvelteKit by the way.