Thank you very much for this. I was dealing with shared state between to components imported to a +layout today and this just made me realize what I was doing wrong
Amazing! As always. Have one question for you: how would you handle shared state across an app? I'm inclined to use the Context API + $state on Classes. It would be really great if you could explore that idea and alternatives on some video ❤ In short: class MyState { value1 = $state(1) value2 = $state(2) } export const createState = () => { setContext('myState', new MyState()) } export const getState = () => { return setContext('myState',) }
Using Class is very cool in Svelte as it will automatically write setters and getters for you in the compiler. However one thing that I found the weakness of doing this is the typing because you can't set the initial value for $state in the constructor. Let's say for example: class Monster { stats = $state() constructor(data:Stats){ this.stats = data } } typescript would scream that .stats could be an undefined so you would have to access it with something like monster?.stats every time. You could pass an initial value to form the shape but then again you would need to worry about side effects in case you're using $effect with it since the constructor would assign the state for the second time. In this case it would just be better to use something like a function wrapper although by doing it you would need to define the setters and getters yourself.
you can simply avoid this issue using type casting : class Monster { stats = $state() as Stats; constructor(data:Stats){ this.stats = data } } now everything works as expected, and no type errors.
@@voidpathlabs thanks for the tip. Biome's linting is forbidding non-null assertion though, so probably the previous solution is best for anyone (or their team) who use Biome
also I tested my original comment several times and found that class constructor is smart enough to reliable handle side effects and since others have point out solutions the Typescript issue I mentioned, you can basically ignore my original post so basically since Class in Svelte assign setters and getters automatically most of the time it is better than to use it than other method IMO. Wrapping $state inside a function also has a drawback that you need to return the variable, resulting more lines and more boilerplate especially for complex states. Not to mention that sometimes we can forget to assign accessors for $state variables and instead return it in function as it is, but Svelte won't tell you if that is not reactive until you hit a bug. (got this bug several times, wish Svelte Language Server would warn me if I forgot to set the getters)
The timing of your content is always perfect, I'm exhausted with people banging on about it being like XYZ or ABC.. if you use them you will see its nothing more than surface. On the complains about needing to box things its always a trivial example like a single number counter.. in the real world you would want some methods to go with that state and so you are naturally going to end up with a wrapped object from a functionlike or class. You also get extra points for the casual use of "willy nilly" 10/10 😂
Okay, I gotta say that had to be one of the BEST youtube videos I have seen in quite some time. Do you think it is possible to make a video about Supabase (Auth&db) With Svelte 5??? What is needed to make this happen?!?!?!?!
Hey, Great Vid! just a little miss I think you did, at 25:05, I think it doesn't use the 'set count(v)' at all, (you are using the increment function which changes the value directly), so it doesn't reach the 'console.log()' that's in there. the only 'console.log()' that is running, is the one in the 'get count()', because it needs to update the variable each time. BTW, I'm totally new to Svelte and JS, so maybe I'm mistaken about something.
I would love for you to do AppWrite and Svelte 5 integration tutorial! (to login, fetch and set user data, update database, upload files and so on). Even if it will be a paid course
Well if svelte used a compiler that is not module scoped, they would be able to turn: export let count = $state(0); into a signal under the hood. So that import count would become import count, setCount
Can you make a video about how we can do API multiple middleware per routes in SvelteKit such that the API can be used by other Frontends apps too and not be dependent on +layout or hooks.
Thanks for making this! 🙏 One thing I don't understand - why is typing a word like ".value" or typing two parens like "()" to call a function such a big deal? I don't mind typing words or parens (or hitting tab and autocompleting them), to me it's such a minor thing it's not even worth thinking about... let alone being so consequential that my "Developer Experience" is noticeably impacted. I personally like Vue's approach here - you never have to waste brain cycles thinking about it when it's "always .value" instead of "maybe .value, maybe nothing"... but just like the alleged "DX" stuff, it's not really that big of a deal.
Allowing state to be accessed as primitive make it closer to Javascript as Svelte intended to be. That's the basic one. I don't understand why would you say"maybe .value, maybe nothing" would be a waste of brain cycles when just about everything in Javascript works that way. Once a state wrapped in $state() it just read like regular variables. Also, you might not mind typing more words for that but many of us do. I'm for example writing a game where I compose several different states into one and it would be a nightmare if I have to write something like game.value.player.value.damage.value.type.value
I think Vue is inconsistent here because they only unwrap the value in the template and having to do `.value` or `value()` for simple state is tedious but that's subjective
@@JoyofCodeDev I mean we have them for a long time now. But i can kinda see how people missed this JS feature since they're rarely shown in framework example code.
@JoyofCodeDev I don't think any of the ones you cited have signals, it's "regular" observables. One with signals is legend but there are a lot of gotchas and compared to view, solid and svelte is not great for DX. The point is DX, you can only mutate state in sync reducers and this makes work with async functions horrible and then you have all the boilerplate to do anything from initializing the store to read from it, and the immutability makes everything harder to do especially with nested objects. Point is, none of react solution have benefit on multiple sides, they only solve 1 issue but do worse in other parts compared to competitors and this also explains why there are so many alternatives, nobody agrees on what global state management should look like.
JSX is everything I was thought not to do some 20 years ago. What happened to "never mix business logic with presentation"? It's impossible to read. Because of the praisal of JSX and contantly jumping out of topic and losing the train of thought, i didn't get past 2 minute mark. Thanks for the attempt, i suppose.
@EliSpizzichino if you would work with just javascript variables and object and avoid things that obscure them (like compilers, hooks or signals) all problems would go away.
@EliSpizzichino you should be able to just use normal variables and not some obscure containers like hooks, runes or signals. Those make it really hard to understand and follow and make things as easy as possible.
Thank you very much for this. I was dealing with shared state between to components imported to a +layout today and this just made me realize what I was doing wrong
This video goes well beyond the obvious and explains runes better than other video available! Even the ones that Rich Harris has made! Great job.
every time i see your videos i start crying, cause they are too good!
Thanks
thank you! 🙏
Thanks! Svelte is so amazing, everytime I do a project with it its a journey with lots of discoveries.
This should be in svelte tutorial, thanks a lot.
Proxied state is my fav
Thank you very much for the valuable information, we will try it.
Amazing! As always.
Have one question for you: how would you handle shared state across an app? I'm inclined to use the Context API + $state on Classes.
It would be really great if you could explore that idea and alternatives on some video ❤
In short:
class MyState {
value1 = $state(1)
value2 = $state(2)
}
export const createState = () => {
setContext('myState', new MyState())
}
export const getState = () => {
return setContext('myState',)
}
I think Huntabyte made a video on this: ruclips.net/video/e1vlC31Sh34/видео.html
Great breakdown!
Good video!
You can do this when destrucuring:
let {count, increment} = $derived(counter)
then you don't have to do count.value
Using Class is very cool in Svelte as it will automatically write setters and getters for you in the compiler. However one thing that I found the weakness of doing this is the typing because you can't set the initial value for $state in the constructor. Let's say for example:
class Monster {
stats = $state()
constructor(data:Stats){
this.stats = data
}
}
typescript would scream that .stats could be an undefined so you would have to access it with something like monster?.stats every time. You could pass an initial value to form the shape but then again you would need to worry about side effects in case you're using $effect with it since the constructor would assign the state for the second time. In this case it would just be better to use something like a function wrapper although by doing it you would need to define the setters and getters yourself.
you can simply avoid this issue using type casting :
class Monster {
stats = $state() as Stats;
constructor(data:Stats){
this.stats = data
}
}
now everything works as expected, and no type errors.
@@komeiltaheri damn you're right, I don't know why I didn't try this before but with 3 different ways to type the state it can be a bit confusing
@@radhy9173 another way is to use a non-null assertion if you're sure that it will be set in the constructor: stats = $state()!;
@@voidpathlabs thanks for the tip. Biome's linting is forbidding non-null assertion though, so probably the previous solution is best for anyone (or their team) who use Biome
also I tested my original comment several times and found that class constructor is smart enough to reliable handle side effects and since others have point out solutions the Typescript issue I mentioned, you can basically ignore my original post
so basically since Class in Svelte assign setters and getters automatically most of the time it is better than to use it than other method IMO. Wrapping $state inside a function also has a drawback that you need to return the variable, resulting more lines and more boilerplate especially for complex states. Not to mention that sometimes we can forget to assign accessors for $state variables and instead return it in function as it is, but Svelte won't tell you if that is not reactive until you hit a bug. (got this bug several times, wish Svelte Language Server would warn me if I forgot to set the getters)
Amazing explanation!!! Thank you.
The timing of your content is always perfect, I'm exhausted with people banging on about it being like XYZ or ABC.. if you use them you will see its nothing more than surface.
On the complains about needing to box things its always a trivial example like a single number counter.. in the real world you would want some methods to go with that state and so you are naturally going to end up with a wrapped object from a functionlike or class.
You also get extra points for the casual use of "willy nilly" 10/10 😂
Okay, I gotta say that had to be one of the BEST youtube videos I have seen in quite some time.
Do you think it is possible to make a video about Supabase (Auth&db) With Svelte 5???
What is needed to make this happen?!?!?!?!
yeah I would love to
@@JoyofCodeDev Honestly man, I would be so greatful!
Cool, from svelte 5 are everything signals? And if so, how does it differ in perf or build size from solid?
I'm not an expert in performance but you can look at krausest.github.io/js-framework-benchmark/current.html
Hey, Great Vid!
just a little miss I think you did, at 25:05, I think it doesn't use the 'set count(v)' at all, (you are using the increment function which changes the value directly), so it doesn't reach the 'console.log()' that's in there. the only 'console.log()' that is running, is the one in the 'get count()', because it needs to update the variable each time.
BTW, I'm totally new to Svelte and JS, so maybe I'm mistaken about something.
yeah it's just a general example
Just when I need this! Nice❤
Best video of svelte out there . ❤
I would love for you to do AppWrite and Svelte 5 integration tutorial! (to login, fetch and set user data, update database, upload files and so on).
Even if it will be a paid course
Gold content as usual 🙏🙏
My memory is out 😂, super sir 🙏
Another banger
❤
Well if svelte used a compiler that is not module scoped, they would be able to turn: export let count = $state(0); into a signal under the hood. So that import count would become import count, setCount
hahaha how I love you bro!! !!, your videos are really a joy, very enriching by the way.
Can you make a video about how we can do API multiple middleware per routes in SvelteKit such that the API can be used by other Frontends apps too and not be dependent on +layout or hooks.
how cool is this
Man. You are making enemies all around. XD
I like to live dangerously
Thanks for making this! 🙏
One thing I don't understand - why is typing a word like ".value" or typing two parens like "()" to call a function such a big deal? I don't mind typing words or parens (or hitting tab and autocompleting them), to me it's such a minor thing it's not even worth thinking about... let alone being so consequential that my "Developer Experience" is noticeably impacted. I personally like Vue's approach here - you never have to waste brain cycles thinking about it when it's "always .value" instead of "maybe .value, maybe nothing"... but just like the alleged "DX" stuff, it's not really that big of a deal.
Allowing state to be accessed as primitive make it closer to Javascript as Svelte intended to be. That's the basic one. I don't understand why would you say"maybe .value, maybe nothing" would be a waste of brain cycles when just about everything in Javascript works that way. Once a state wrapped in $state() it just read like regular variables. Also, you might not mind typing more words for that but many of us do. I'm for example writing a game where I compose several different states into one and it would be a nightmare if I have to write something like game.value.player.value.damage.value.type.value
I think Vue is inconsistent here because they only unwrap the value in the template and having to do `.value` or `value()` for simple state is tedious but that's subjective
I really dont get why people oppose using accessors. I think they make the code cleaner and easier to understand.
I think some people are unfamiliar with them and Svelte doesn't give you a wrapper like `ref` to ignore them since there's proxied state and classes
@@JoyofCodeDev I mean we have them for a long time now. But i can kinda see how people missed this JS feature since they're rarely shown in framework example code.
Can we have type safety in .svelte?
Svelte now has native TypeScript support
Do a video about integrate svelte runes with React to replace Redux xD
from what I know React has popular state management libraries that use some form of signals like MobX, Zustand and Jotai you can use instead
@JoyofCodeDev I don't think any of the ones you cited have signals, it's "regular" observables. One with signals is legend but there are a lot of gotchas and compared to view, solid and svelte is not great for DX.
The point is DX, you can only mutate state in sync reducers and this makes work with async functions horrible and then you have all the boilerplate to do anything from initializing the store to read from it, and the immutability makes everything harder to do especially with nested objects.
Point is, none of react solution have benefit on multiple sides, they only solve 1 issue but do worse in other parts compared to competitors and this also explains why there are so many alternatives, nobody agrees on what global state management should look like.
Give me that Lualine config, i am struggling
I think with the power of store and $state much boilerplates can be reduced
I bet 99% of shared state use cases can just be dealt with proxied state and it should probably be the first thing in the docs.
JSX is everything I was thought not to do some 20 years ago. What happened to "never mix business logic with presentation"? It's impossible to read. Because of the praisal of JSX and contantly jumping out of topic and losing the train of thought, i didn't get past 2 minute mark. Thanks for the attempt, i suppose.
your concerns are in a single file, so it's fine
how do you navigate so fast?
I have a video on that: ruclips.net/video/QHfnVtgU2II/видео.html
As I understand it, all runes work with signals. I have a desire to replace all the old designs with runes, but then I understand that this is wrong.
if you mean stores then yes
@10:52 is how you really feel about this approach
I hate this keyboard 😂
@@JoyofCodeDev 😂😂😂
Don't Fear the Runes
12:00 Svelte 5 lost me there. What if I have many values to get and set...
you can use a Proxy object or a class
$count was 100x better than count.value and I will die on that hill
you could make a preprocessor 😎
TLDR: Imported unwrapped states cannot be reactive
When are you doing a full project using svelte? 🙂
Again solving problems that you should not have in the first place
what you mean?
@EliSpizzichino if you would work with just javascript variables and object and avoid things that obscure them (like compilers, hooks or signals) all problems would go away.
Absolutely!
@EliSpizzichino you should be able to just use normal variables and not some obscure containers like hooks, runes or signals. Those make it really hard to understand and follow and make things as easy as possible.
And they told me rxjs observables in angular are overengineered... 🥲