Different Ways To Share State In Svelte 5

  Рет қаралды 15,436

Joy of Code

Joy of Code

Күн бұрын

Пікірлер: 122
@marlopainter8246
@marlopainter8246 2 ай бұрын
This was the best video of yours, and the best Runes video I've seen. You completely demystified them AND opened me up to using Classes. Thank you! As a bonus, I love your presentation, delivery, and humor you mix in. Your love of coding and Svelte shine through and is infectious.
@JS-ud8zk
@JS-ud8zk Ай бұрын
Took a few iterations on docs, blog post(s), and finally this video helped it all click. Svelte 5 is absolutely amazing. Thanks!
@rogerpence
@rogerpence 3 ай бұрын
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.
@c.1977
@c.1977 3 ай бұрын
Thanks
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
thank you! 🙏
@victorbuikem
@victorbuikem 3 ай бұрын
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
@Redtiger7777
@Redtiger7777 Ай бұрын
Thanks for this :)
@gabriel_export
@gabriel_export Ай бұрын
Best video on Svelte 5 state!
@joshcollinsworth9471
@joshcollinsworth9471 2 ай бұрын
This is exactly the primer on Svelte 5 shared state I needed. Thank you!
@lifeparticles
@lifeparticles 2 ай бұрын
Thanks!
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
thank you! 🙏
@phicomingatya
@phicomingatya Ай бұрын
14:00 I use: const { count, increment } = $derived(counter);
@mrocholl
@mrocholl Ай бұрын
Are you planning on making a video with store vs state usecases? That would be awesome. Thx for your amazing videos!
@JoyofCodeDev
@JoyofCodeDev Ай бұрын
you only need runes for state
@phide1312
@phide1312 14 күн бұрын
This video helped me a lot with Svelte 5, thanks!
@nomadtrails
@nomadtrails 2 ай бұрын
You really delivered on this one! So far this is the best Svelte 5 vid I have come across, thanks!
@viniciusrvieira
@viniciusrvieira 2 ай бұрын
Valeu!
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
thank you! 🙏
@justingolden21
@justingolden21 2 ай бұрын
Super well done, both detailed and yet not confusing
@luisdavidmartinezfundora8224
@luisdavidmartinezfundora8224 Ай бұрын
This is a master class ❤
@ridass.7137
@ridass.7137 3 ай бұрын
Thanks! Svelte is so amazing, everytime I do a project with it its a journey with lots of discoveries.
@anonimoanonimo1750
@anonimoanonimo1750 2 ай бұрын
every time i see your videos i start crying, cause they are too good!
@omomer3506
@omomer3506 2 ай бұрын
After your awesome explanation, for my mental model, 1. Is classes then 2. Is accessors If its a very simple state then proxy would be okay Also i am such a child i giggled at getC**t
@mattl7599
@mattl7599 2 ай бұрын
Classes look so good. I think that’ll be my preferred approach going forward.
@user-ke8ty5ds7r
@user-ke8ty5ds7r Ай бұрын
Interesting, but I don't get why the import is an issue for the compiler. The export is in a Svelte file where compiler knows which values are runes and its imported to another Svelte file where the compiler knows which values are runes. So, its known on both sides if a value is a rune, so why can't it generate the wrapper automatically, just like with all the other functions that are generated in the background.
@ryansolid
@ryansolid 2 ай бұрын
What's interesting is after that whole video of explanation of all the ways to wrap and share state there was no solution that actually got away from needing to call a function or a `.value` when combined with destructuring. Even with the compiler this problem isn't completely solvable ergonomically. The class trick of not needing to write the getters is nice but doesn't change the consumption side. If this was accepted from the beginning it could have saved everyone a lot of time.
@Bhide.Svelte
@Bhide.Svelte 19 күн бұрын
totally agree
@Bhide.Svelte
@Bhide.Svelte 19 күн бұрын
check this out : You can do this when destrucuring: let {count, increment} = $derived(counter)
@adrienetaix
@adrienetaix 2 ай бұрын
That should be a page in the Svelte documentation (or maybe I missed it), it's so clear and with lots of options !
@gorbulevsv
@gorbulevsv 2 ай бұрын
Thank you very much for the valuable information, we will try it.
@Александр-ч4п5ъ
@Александр-ч4п5ъ 3 ай бұрын
This should be in svelte tutorial, thanks a lot. Proxied state is my fav
@mit3y
@mit3y 2 ай бұрын
Great video -- i also really like the theme of your browser, what browser is it? how did you theme it?
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
I use Brave but I hide window titles in Linux so maybe that's why it looks different to you
@danielmears_uk
@danielmears_uk 16 күн бұрын
Absolutely first class video
@Lapatate-s1l
@Lapatate-s1l 3 ай бұрын
Best video of svelte out there . ❤
@EnricoSacchetti
@EnricoSacchetti 2 ай бұрын
Great breakdown!
@user-eg4qz9yc7e
@user-eg4qz9yc7e 2 ай бұрын
#count: number = $state(0) Can we specify the type on the left side of initialize variables? Feels cleaner especially when we start making type models to be passed onto the backend.
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
sure if TypeScript can't infer the type
@noam2663
@noam2663 2 ай бұрын
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.
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
yeah it's just a general example
@Kevin192291
@Kevin192291 3 ай бұрын
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?!?!?!?!
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
yeah I would love to
@Kevin192291
@Kevin192291 3 ай бұрын
@@JoyofCodeDev Honestly man, I would be so greatful!
@dei8bit
@dei8bit 3 ай бұрын
hahaha how I love you bro!! !!, your videos are really a joy, very enriching by the way.
@thedelanyo
@thedelanyo 2 ай бұрын
All these examples are really nice, but are only around `count`, yet no one is using count in production 😊😊😅
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
I'm going to make a visitor counter right now
@lungarella-raffaele
@lungarella-raffaele 2 ай бұрын
Gold content as usual 🙏🙏
@radhy9173
@radhy9173 3 ай бұрын
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.
@komeiltaheri
@komeiltaheri 3 ай бұрын
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.
@radhy9173
@radhy9173 3 ай бұрын
@@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
@voidpathlabs
@voidpathlabs 2 ай бұрын
@@radhy9173 another way is to use a non-null assertion if you're sure that it will be set in the constructor: stats = $state()!;
@radhy9173
@radhy9173 2 ай бұрын
@@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
@radhy9173
@radhy9173 2 ай бұрын
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)
@dustin6336
@dustin6336 Ай бұрын
"Cannot assign to 'count' because it is an import" is the error I am getting when attempting to centralize my runes. The workaround (and it is just that, a workaround) of `$state({ value: 0 })` works great, but starts to feel like, "why didn't I just use Vue for this?" I really love(d) Svelte up until 5. Still trying, but seems like the *joy* and *DX* are waning each step of the way.
@dustin6336
@dustin6336 Ай бұрын
Switching back to `writable(0)` for now... at least this way I don't have to write the wrapper myself for every piece of shared state, and I'll get to maintain some of that sweet sweet Svelte DX for a little bit longer.
@ucielsola
@ucielsola 3 ай бұрын
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',) }
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
I think Huntabyte made a video on this: kzbin.info/www/bejne/m2LZnXZpZribaZY
@budivoogt491
@budivoogt491 Ай бұрын
@@JoyofCodeDev Looks like a valid approach to me! But I run into one issue -- how can I destructure reactive properties from a class, once I import it using getState()?
@7heMech
@7heMech 3 ай бұрын
Another banger
@martinblasko5795
@martinblasko5795 3 ай бұрын
Just when I need this! Nice❤
@stanislavdunajcan2703
@stanislavdunajcan2703 3 ай бұрын
Amazing explanation!!! Thank you.
@StephenFosterUK
@StephenFosterUK 3 ай бұрын
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 😂
@Darthtrooper14
@Darthtrooper14 Ай бұрын
How do I make my setup look like this? Like the padding, background?
@skowne
@skowne 3 ай бұрын
Good video! You can do this when destrucuring: let {count, increment} = $derived(counter) then you don't have to do count.value
@erickmoya1401
@erickmoya1401 2 ай бұрын
Man. You are making enemies all around. XD
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
I like to live dangerously
@EliSpizzichino
@EliSpizzichino 2 ай бұрын
The state management docs should be updated with at least a link to this video
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
we can improve it 😄
@greendsnow
@greendsnow 3 ай бұрын
12:00 Svelte 5 lost me there. What if I have many values to get and set...
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
you can use a Proxy object or a class
@devgauravjatt
@devgauravjatt 3 ай бұрын
My memory is out 😂, super sir 🙏
@mikemcculley
@mikemcculley 11 күн бұрын
Sorry. Somewhat new to frontend in general here. Why not define state and export an object? Why is the function or class better? At 12:30?
@АртемЗеленов-л1р
@АртемЗеленов-л1р 3 ай бұрын
how cool is this
@bradyfractal6653
@bradyfractal6653 3 ай бұрын
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.
@radhy9173
@radhy9173 3 ай бұрын
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
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
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
@OuterSpaceCat
@OuterSpaceCat 3 ай бұрын
@saiphaneeshk.h.5482
@saiphaneeshk.h.5482 3 ай бұрын
Cool, from svelte 5 are everything signals? And if so, how does it differ in perf or build size from solid?
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
I'm not an expert in performance but you can look at krausest.github.io/js-framework-benchmark/current.html
@supbra1
@supbra1 3 ай бұрын
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
@helsingking281
@helsingking281 2 ай бұрын
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.
@bene0817
@bene0817 3 ай бұрын
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
@thedelanyo
@thedelanyo 2 ай бұрын
I think with the power of store and $state much boilerplates can be reduced
@gorbulevsv
@gorbulevsv 2 ай бұрын
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.
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
if you mean stores then yes
@Anonymous-hv7fh
@Anonymous-hv7fh Күн бұрын
I have a qst When u used the export function thing If i called it in component1 made it = 5 Then i called it in component2 does it stays 5 or it's 0
@pixsa
@pixsa 2 ай бұрын
Give me that Lualine config, i am struggling
@akza0729
@akza0729 3 ай бұрын
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.
@Lemmy4555
@Lemmy4555 3 ай бұрын
Do a video about integrate svelte runes with React to replace Redux xD
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
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
@Lemmy4555
@Lemmy4555 3 ай бұрын
@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.
@simpingsyndrome
@simpingsyndrome 3 ай бұрын
Can we have type safety in .svelte?
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
Svelte now has native TypeScript support
@TheGargalon
@TheGargalon 3 ай бұрын
$count was 100x better than count.value and I will die on that hill
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
you could make a preprocessor 😎
@phoneywheeze
@phoneywheeze Күн бұрын
on the same hill with you. why go back to javascript?
@TheGargalon
@TheGargalon 13 сағат бұрын
@@phoneywheeze salute
@TheVertical92
@TheVertical92 3 ай бұрын
I really dont get why people oppose using accessors. I think they make the code cleaner and easier to understand.
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
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
@TheVertical92
@TheVertical92 3 ай бұрын
@@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.
@phoneywheeze
@phoneywheeze Күн бұрын
​@@TheVertical92i think it's because most people used svelte for the magic, and not to be just like javascript. initially even rich harris developed the framework to be accessible for non programmers. Svelte changed from "How javascript should've worked reactively" to "You have to use getters and setters, because that's how javascript works." If I wanted to use getters and setters I'd just use vanialla javascript.
@helsingking281
@helsingking281 2 ай бұрын
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.
@JoyofCodeDev
@JoyofCodeDev 2 ай бұрын
your concerns are in a single file, so it's fine
@whydoyouneedmyname_
@whydoyouneedmyname_ 3 ай бұрын
Don't Fear the Runes
@paololucchesi2827
@paololucchesi2827 3 ай бұрын
TLDR: Imported unwrapped states cannot be reactive
@fottymutunda6320
@fottymutunda6320 3 ай бұрын
how do you navigate so fast?
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
I have a video on that: kzbin.info/www/bejne/h3nJn4mqnLplf6s
@anotherxyear
@anotherxyear 3 ай бұрын
@10:52 is how you really feel about this approach
@JoyofCodeDev
@JoyofCodeDev 3 ай бұрын
I hate this keyboard 😂
@anotherxyear
@anotherxyear 3 ай бұрын
@@JoyofCodeDev 😂😂😂
@knolljo
@knolljo Ай бұрын
I had a good laugh 😂
@prestongovender5715
@prestongovender5715 3 ай бұрын
When are you doing a full project using svelte? 🙂
@StephanHoyer
@StephanHoyer 3 ай бұрын
Again solving problems that you should not have in the first place
@EliSpizzichino
@EliSpizzichino 3 ай бұрын
what you mean?
@StephanHoyer
@StephanHoyer 3 ай бұрын
@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.
@Mohamed-tk5nc
@Mohamed-tk5nc 3 ай бұрын
Absolutely!
@StephanHoyer
@StephanHoyer 3 ай бұрын
@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.
@f-Yoda
@f-Yoda 2 ай бұрын
And they told me rxjs observables in angular are overengineered... 🥲
Easy Auth, Database, i18n Setup And More For SvelteKit
12:21
Joy of Code
Рет қаралды 10 М.
Master The Svelte Context API
18:07
Joy of Code
Рет қаралды 10 М.
UFC 310 : Рахмонов VS Мачадо Гэрри
05:00
Setanta Sports UFC
Рет қаралды 1,2 МЛН
So Cute 🥰 who is better?
00:15
dednahype
Рет қаралды 19 МЛН
Гениальное изобретение из обычного стаканчика!
00:31
Лютая физика | Олимпиадная физика
Рет қаралды 4,8 МЛН
20 Svelte Features You Missed During Advent Of Svelte
20:07
Joy of Code
Рет қаралды 12 М.
Use Svelte 5 Snippets To Reuse Markup Without Creating Components
17:41
Svelte 5 Is Like React, But Better
19:33
Theo - t3․gg
Рет қаралды 88 М.
Rich Harris | Svelte 5: Beyond Components | ViteConf 2024
5:05
Global Stores Are Dangerous
11:48
Huntabyte
Рет қаралды 18 М.
Understanding Effects In Svelte 5 And When To Use Them
27:31
Joy of Code
Рет қаралды 10 М.
How To Handle Permissions Like A Senior Dev
36:39
Web Dev Simplified
Рет қаралды 384 М.
Svelte 5's Secret Weapon: Classes + Context
18:14
Huntabyte
Рет қаралды 33 М.
UFC 310 : Рахмонов VS Мачадо Гэрри
05:00
Setanta Sports UFC
Рет қаралды 1,2 МЛН