Different Ways To Share State In Svelte 5

Поделиться
HTML-код
  • Опубликовано: 12 ноя 2024

Комментарии • 79

  • @victorbuikem
    @victorbuikem 4 дня назад +16

    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

  • @rogerpence
    @rogerpence 3 дня назад +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.

  • @anonimoanonimo1750
    @anonimoanonimo1750 День назад

    every time i see your videos i start crying, cause they are too good!

  • @c.1977
    @c.1977 4 дня назад +15

    Thanks

  • @ridass.7137
    @ridass.7137 4 дня назад +3

    Thanks! Svelte is so amazing, everytime I do a project with it its a journey with lots of discoveries.

  • @Александр-ч4п5ъ
    @Александр-ч4п5ъ 3 дня назад

    This should be in svelte tutorial, thanks a lot.
    Proxied state is my fav

  • @gorbulevsv
    @gorbulevsv День назад

    Thank you very much for the valuable information, we will try it.

  • @ucielsola
    @ucielsola 4 дня назад +5

    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  4 дня назад +2

      I think Huntabyte made a video on this: ruclips.net/video/e1vlC31Sh34/видео.html

  • @EnricoSacchetti
    @EnricoSacchetti День назад

    Great breakdown!

  • @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

  • @radhy9173
    @radhy9173 3 дня назад +2

    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 дня назад +2

      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 дня назад +2

      @@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 День назад

      @@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 День назад

      @@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 День назад

      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)

  • @stanislavdunajcan2703
    @stanislavdunajcan2703 4 дня назад

    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 😂

  • @Kevin192291
    @Kevin192291 3 дня назад +2

    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 дня назад +1

      yeah I would love to

    • @Kevin192291
      @Kevin192291 3 дня назад

      @@JoyofCodeDev Honestly man, I would be so greatful!

  • @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

  • @noam2663
    @noam2663 День назад

    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  6 часов назад

      yeah it's just a general example

  • @martinblasko5795
    @martinblasko5795 4 дня назад +1

    Just when I need this! Nice❤

  • @Lapatate-s1l
    @Lapatate-s1l 4 дня назад +2

    Best video of svelte out there . ❤

  • @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

  • @lungarella-raffaele
    @lungarella-raffaele День назад

    Gold content as usual 🙏🙏

  • @devgauravjatt
    @devgauravjatt 4 дня назад +1

    My memory is out 😂, super sir 🙏

  • @7heMech
    @7heMech 4 дня назад +4

    Another banger

  • @OuterSpaceCat
    @OuterSpaceCat 4 дня назад +2

  • @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

  • @dei8bit
    @dei8bit 3 дня назад

    hahaha how I love you bro!! !!, your videos are really a joy, very enriching by the way.

  • @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.

  • @АртемЗеленов-л1р
    @АртемЗеленов-л1р 2 дня назад

    how cool is this

  • @erickmoya1401
    @erickmoya1401 День назад

    Man. You are making enemies all around. XD

  • @bradyfractal6653
    @bradyfractal6653 4 дня назад

    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

  • @TheVertical92
    @TheVertical92 4 дня назад

    I really dont get why people oppose using accessors. I think they make the code cleaner and easier to understand.

    • @JoyofCodeDev
      @JoyofCodeDev  4 дня назад

      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 4 дня назад

      @@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.

  • @simpingsyndrome
    @simpingsyndrome 3 дня назад

    Can we have type safety in .svelte?

    • @JoyofCodeDev
      @JoyofCodeDev  3 дня назад

      Svelte now has native TypeScript support

  • @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.

  • @pixsa
    @pixsa День назад

    Give me that Lualine config, i am struggling

  • @thedelanyo
    @thedelanyo День назад

    I think with the power of store and $state much boilerplates can be reduced

  • @helsingking281
    @helsingking281 День назад

    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.

  • @helsingking281
    @helsingking281 День назад

    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  6 часов назад

      your concerns are in a single file, so it's fine

  • @fottymutunda6320
    @fottymutunda6320 4 дня назад

    how do you navigate so fast?

    • @JoyofCodeDev
      @JoyofCodeDev  3 дня назад +1

      I have a video on that: ruclips.net/video/QHfnVtgU2II/видео.html

  • @gorbulevsv
    @gorbulevsv День назад

    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.

  • @leshok
    @leshok 4 дня назад +2

    @10:52 is how you really feel about this approach

    • @JoyofCodeDev
      @JoyofCodeDev  4 дня назад +1

      I hate this keyboard 😂

    • @leshok
      @leshok 4 дня назад

      @@JoyofCodeDev 😂😂😂

  • @whydoyouneedmyname_
    @whydoyouneedmyname_ 2 дня назад

    Don't Fear the Runes

  • @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

  • @TheGargalon
    @TheGargalon 3 дня назад

    $count was 100x better than count.value and I will die on that hill

    • @JoyofCodeDev
      @JoyofCodeDev  6 часов назад

      you could make a preprocessor 😎

  • @paololucchesi2827
    @paololucchesi2827 3 дня назад

    TLDR: Imported unwrapped states cannot be reactive

  • @prestongovender5715
    @prestongovender5715 4 дня назад

    When are you doing a full project using svelte? 🙂

  • @StephanHoyer
    @StephanHoyer 4 дня назад +1

    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 19 часов назад

    And they told me rxjs observables in angular are overengineered... 🥲