I have a few dozens of reactive primitive values (like e.g. div_status = "frozen"
) which I need to pass between component/module boundaries, including +page.svelte
files and svelte.js
modules. These values represent changable properties of the UI, and will hence influence (a) styles as well as (b) if-else blocks inside some event listeners for user interaction. Importantly, the values need to be reactively on a drag-level, since the UI must respond while the user is dragging (e.g. hovering over a dropzone, dragging for a specific distance, etc.)
Transforming my code base to Svelte 5, I'm not sure, whether to use stores or $state()
for this use case.
My problem with stores is, that I don't manage to use them inside the export functions in the
svelte.js
modules. Furthermore they are hard to refactor.My problem with using
$state()
for my primitives (like$state("frozen")
) is that I have to complicate things in order not to reassign/overwrite the state: So, to just mutate their values, I would either group multiple primitives together to Object Arrays or blow them up individually (e.g.div_status = {value: "frozen"}
).
Lastly, I am confused, whether I should look into how getters/setters work and whether the choice of either stores or $state()
depends on my choice of using context-API or just passing them around as props. All in all I'm looking for a solution that is easy to refactor.
Update
I ended up using $state together with getters/setters. For anybody reading this until the official Svelte 5 Docs are out: I very much recommend watching this video of Rich Harris, which explains how to do this, and why it's NOT MORE code to write, even at first glance, you may think so.
I don't use stores any more, but for anybody interested in using them I'll write my code in a separate answer to this question. It will also work in in svelte.js
files.