After almost 18 months of development, comprising thousands of commits from dozens of contributors, Svelte 5 is finally stable.
Svelte got a lot better. RUNES are just awesome.
Let's see how we can create a reusable reactive logic for managing global state.
Previously, we used stores
, which had a different API and behavior, that created a disconnect and inconsistencies.
Now we can use runes in .svelte.ts
or .svelte.js
files. Define a shared reusable reactive logic with runes and access from any .svelte
component. This eliminates prop drilling, reduce boilerplate, simplify store setup and better maintainability.
#. Example case
Let's take a look at sample code, a dark/light theme management.
Here, I created a color_scheme.svelte.ts
file inside /lib/stores/
.
color_scheme.svelte.ts
This color_scheme
is our main state here, this can be accessed from any component and they get updated whenever this state value changes.
But we can't export state from here, it will show error. Instead, we need a function which returns the value of this state and export that function instead.
color_scheme.svelte.ts
We can just import this function in any component and it will just work.
Now comes the interesting part, what if we also want to do something when this state value changes? Yes, we can use another rune called $effect
in this same file.
color_scheme.svelte.ts
(Ignore the logic inside it), Now whatever logic inside that $effect
will just run whenever color_scheme
changes.
But why $effect
is wrapped inside another rune $effect.root
, since this file is not a Svelte component, we can't just use $effect
. $effect.root
allows us to use nested effects outside of component initialization phase.
Official docs about $effect.root
We can use this in a random component like:
svelte
Full code:
color_scheme.svelte.ts