export const state: State = $state({ user: undefined });
The problem is, this creates global (server-wide) state, when it should be "user-local" global state.
export const state: State = $state({ user: undefined });
The problem is, this creates global (server-wide) state, when it should be "user-local" global state.
One pattern that I love to use in my SvelteKit projects is returning writable stores from the layout’s load function. This makes it possible to fetch data from the server (for example the user object for the logged in user), and then you make this object available as a writable reactive store throughout the whole application. So when the user updates their username or avatar, you do the PUT request to the server and you get the updated user object back from the server as the response, you can simply update the $user writable store value and every place in your app where you show the user object gets updated immediately.
However, to do that, you have to put the $state value in a callback (or getter/setter object) in the parameters of the function. This feels rather clunky and un-Svelte like. Here's an example of what I mean.
This works. See their demo.
let myObj = { ...$get({foo, bar}) }
This was offered as a solution to https://github.com/sveltejs/svelte/issues/14404
Frontend frameworks are a positive sum game! Svelte has no monopoly on the compiler paradigm either. Just like I think React is worth learning for the mental model it imparts, where UI is a (pure) function of state, I think the frontend framework-as-compiler paradigm is worth understanding. We're going to see a lot more of it because the tradeoffs are fantastic, to where it'll be a boring talking point before we know it.
It adds a few constructs to the language to solve one of the most complex problems in UI development — state management.
The $ contract for auto-subscribing is lovely in its simplicity and flexibility. You can adapt your own preferred state-management pattern or library, with or without Svelte stores as helpers. Svelte does not fuss about how you want to manage your state.
Stores are global state. While context is local state.
Notice it's not related to components. Another crucial difference is that it's accessible from outside of components. And good way to determine where goes where is to ask yourself, can this particular state and functionality still makes sense outside of the displayed component?
Made analogy with internal combustion engine, which has 1000s of parts, with the "radical simplicity" approach taken by Tesla: they use an electric motor, which only has 2 components!
comparison: Sapper vs. Gatsby
State management is also easier. Instead of importing hooks and using setters, you just define a property within the script tags. You then change the value by re-assigning it (not mutating the original value).