Reactivity Explained

Поделиться
HTML-код
  • Опубликовано: 3 авг 2024
  • A look at how web frameworks are implementing reactivity.
    Miško's article - www.builder.io/blog/reactivit....
    💬 Topics:
    - What is reactivity?
    - Signals vs Observables vs Value dirty checking;
    - React vs Svelte vs Vue vs Qwik vs Solid.
    - Performance in frontend apps.
    #javascript
    Patreon: / awesomeclub

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

  • @philipdamianik3567
    @philipdamianik3567 Год назад +18

    As a fan of Sveltes approach to reactivity I wanted to expand a bit on your analysis of Sveltes reactivity after looking through and debugging the compiler output of the Svelte v4.1.1 tutorial "Reactivity / Assignments". TLDR: Sveltes reactivity seems to be fine-grained and only updates the necessary DOM elements (and doesn't rerun most of the component at any point, only the reactivity handlers).
    When the Svelte compiler detects an assignment it replaces it with a call to $$invalidate(dirty, new_value); which will first check if the value has actually changed (i.e. the assignment wasn't for the same value) and if it did change it will set the appropriate bit inside the component-wide dirty field. This dirty field is a flag value where each bit indicates a change for a certain reactive value of the component. Then Svelte calls the component wide update() function (the "p" function from the blog post) which handles changes to the dirty field and therefore updates to any reactive values. If the reactive value is used directly in the DOM the associated text node is simply updated with the new value. If on the other hand the value is used in an expression like { likes < 15 ? "a few" : "a lot" } or { like + " 👍" }, these values are diffed with the updated likes value and the DOM will only change if the value has changed (e.g. when likes goes from 8 to 9 we don't need to change the former example. Additionally a change to a reactive value would also recalculate any dependent value like $: text = `You have ${likes} likes` and if a reactive value is used as a prop the new value will simply be used in an $$invalidate() call inside the nested component.
    Edit: the difference between this approach to reactivitiy and something like signals seems to be the unit of reactivity: in Sveltes case updates to reactive values are handled at the component level whereas signals handle the updates themselves. Disclaimer: I have never used a signal based framework like SolidJS or Qwick.

    • @JDalmasca
      @JDalmasca Год назад

      Came to say this too. Good explanation.

    • @awesome-coding
      @awesome-coding  Год назад +2

      Thank you for the detailed explanation! I really appreciate it!

  • @BizzonedCorp
    @BizzonedCorp Год назад +12

    Ryan Carniato has a really good explanation of signals and how Solid's reactivity works on Frontend Masters. Imho, the really neat part of Solid is that it just uses the callstack to model the reactive graph. Basically, a signal is like an observable, i.e. a scope with a list of subscribers that exposes expose a getter and a setter function. However, unlike observables which only "push" their values to their subscribers, signals have a hybrid push/pull behavior. You create transformed values from signals by wrapping the getter function in layers of other functions (what Ryan calls "computed values"). Then, when you go use the computed value (an "effect", e.g. rendering a DOM update), you keep unwrapping the layers and pushing them onto the callstack until you reach one or more signals at the bottom, and, once that happens, you start popping things off the callstack again, i.e. when a change is triggered, you keep "digging" until you find the signal(s) that caused it and then "climb" back up again. So we have a key feature: a) signals are always at the bottom of the reactive hierarchy. This wouldn't be all that special on its own, but there's another key feature: b) you only ever subscribe to signals. The cool part about having these two feature combined is that they solve the diamond problem: only the things at the very bottom of the reactive hierarchy trigger updates, and we have a way of digging through the layers of computation to get to them (callstack), so whatever signal changes we can be sure it will only trigger one update in all of its dependencies!
    (to give the full picture, it would be also good to explain how effects and computed values work, but this is already long enough, if you're interested go watch Ryan's videos instead!)

  • @mawill432
    @mawill432 Год назад +9

    Misko is the man. I love angular, and I love qwik. Great vid!

  • @kevintale2608
    @kevintale2608 Год назад +24

    Hi!
    Just to clarify a bit about the Angular part. Angular does not rely on Observables at all to detect if it should update components templates but rather on zone.js, a third party library that, in short, tells when to run change detection. Change detection will check if the components properties are different that their previous state and update the views that use them accordingly.
    Note that Angular has introduced Signals 3 month ago and soon zone.js will be entirely removed.
    So in a few month Angular CD (change detection) will behave completely differently than it used to and will be comparable to how SolidJS works.
    But anyway, thanks for the video and the hard work you put on it :)

    • @awesome-coding
      @awesome-coding  Год назад +4

      Thank you for the clarification!

    • @Wielorybkek
      @Wielorybkek Год назад

      Not sure where this idea comes from... Observables indeed trigger the change detection. I did a small test like this:
      ngAfterViewInit(): void {
      interval(1000).pipe(take(6)).subscribe();
      }
      I added a dummy observable in my component that just counts from 0 to 5. It does not have any impact on template. But still, when I do this:
      ngDoCheck(): void {
      console.log("default change detection");
      }
      I get a console log every second.

    • @kevintale2608
      @kevintale2608 Год назад +1

      @@Wielorybkek they do trigger CD but they are not involved in how the internals of CD works in Angular. This video is about how the different frameworks update their templates.

    • @oriel-elkabets
      @oriel-elkabets Год назад +4

      ​ @piotrkoodziejski8718
      Actually, observables by themselves do not trigger Change Detection (CD). The reason CD was triggered in your case is because of the interval.
      Also, checking for CD in the DoCheck hook will not always be correct. It depends on whether the component's ChangeDetectionStrategy is set to Default or OnPush. When it is set to Default, it will work correctly. However, with OnPush, when there is a CD cycle, the DoCheck will run - even if Angular will not check this component.
      I think the best approach is to bind a function that returns something to the template and log from within that function.

    • @Wielorybkek
      @Wielorybkek Год назад

      @@oriel-elkabets Thank you! Great insight

  • @alex_constantin
    @alex_constantin Год назад +3

    One of the most interesting videos on the subject. Thank you!

  • @slluxxx
    @slluxxx Год назад +44

    ill probably forever stick with Vue. Sveltekit is my second favorite out of them. Ive actually never really liked React nor Angular

    • @chrizzzly_hh
      @chrizzzly_hh Год назад +7

      Imho, vue brings the best bridge between beginners who want to extend their knowledge and have an easier way for reactivity, and experts who know better principles of structuring and developing a huge project.
      At the end - go with the framework/language that works best for you and your needs

    • @Xe054
      @Xe054 Год назад +4

      I'm trying them all with an open mind and just having fun with it. Angular is so different from React but still interesting. I'm trying Svelte and Vue next, both of which have very smart maintainers. It's all about forming your own opinions, preferences, and growing as a developer.

    • @slluxxx
      @slluxxx Год назад +5

      ​@@Xe054 ​ and @xxxfanta agreed 100% but i've ben doing fullstack development for over 10 years now and formed my opinions and workflow :D You should always learn new things and must do so to keep up with technology but jumping on the next best framework to catch the hypetrain is counterproductive if you are working large scale.

    • @soundrightmusic
      @soundrightmusic Год назад +6

      I love Vue its my personal favorite framework. Qwik is really cool though. The "optimized by default philosophy is gold". It will be interesting to see how vue vapor impacts the whole discussion.

  • @coder_one
    @coder_one Год назад +1

    I look forward to reading any material about Qwik!

  • @soundrightmusic
    @soundrightmusic Год назад

    Great video great article. Reactivity can quickly become a complicated subject. So most just point to metrics and buzz words. Rather than even try to explain whats going on.

  • @ErikHejl
    @ErikHejl Год назад +1

    Probably your best video I've seen to date. Thank you.

    • @awesome-coding
      @awesome-coding  Год назад

      This really means a lot to me! Thank you so much!

  • @mfpears
    @mfpears Год назад +3

    This isn't reactivity. This is one _type_ of reactivity: Synchronization. Asynchronous reactivity (functional reactive programming) is equally important.

  • @xtraszone
    @xtraszone 7 дней назад

    Just 1 mistake:
    Vue 3 uses signals like approach using proxies under the hood and it never re-renders the component on every update.
    You can even try adding console.log the the root of script and see if it prints it on every updates

  • @user-se2ee8fz1p
    @user-se2ee8fz1p Год назад +1

    Looking forward on how solid handles reactivity. since its not much explained in this video

    • @awesome-coding
      @awesome-coding  Год назад +2

      Sure thing - I'll work on something more detailed for that!

    • @vaisakhkm783
      @vaisakhkm783 Год назад

      yes i would love to..

  • @thedelanyo
    @thedelanyo Год назад +2

    vdom was then a killer feature for Reactjs,,, i guess now it's the one killing it

  • @netssrmrz
    @netssrmrz 5 месяцев назад

    Good video. 👍 informative. Personally, as someone that prefers to just use the platform, I feel the concept is of trivial value. Seems like over engineered getters and setters.

    • @awesome-coding
      @awesome-coding  5 месяцев назад

      Fair enough! Thanks for your feedback!

  • @Makeshitjusbecuz
    @Makeshitjusbecuz Год назад

    I get that reacts thing is kinda messy, but its not the endgame either. You could just restructure that code differently. And avoid unwanted component from re rendering.
    Granted it requires quite some time and trial and error to reach that stage and things like svelte allow you to get performant website much easier

    • @awesome-coding
      @awesome-coding  Год назад

      I agree with that, and I think it's achievable in small teams of experienced devs.
      However, in large teams with people having different skill levels I believe this adds another layer of complexity in the dev process - more time spent in PRs and so on.

  • @TechBuddy_
    @TechBuddy_ Год назад

    This is exactly what I want, this is not pointless at all but IMHO the AVD and viewer retention will be not as good. Awesome video anyways
    But things are changing very fast svelte 5 will be a complete rewrite of the compiler so it will be much closer to solid soon. Angular also has signals now they're gonna remove zone js so it will also be closer and react uhmmm... React forgot should make it faster IG IDK. I don't know whats happening with vue but evan is a genius so he might be cooking something up exciting times

    • @awesome-coding
      @awesome-coding  Год назад

      What's your take on Qwik? After some discussions with the Qwik team (a video will follow soon), I'm pretty blown away by the things they are doing behind the scenes!

    • @TechBuddy_
      @TechBuddy_ Год назад

      @@awesome-coding qwik is awesome I looked at the src and sooo much cool stuff is happening and I love it. Only thing that is stopping me from using it is the supporting libs. Solid has the same problem ( but they are adding new libs very rapidly ). You can't just use any library written in vanilla js you need wrappers around them and it's the problem with all jsx based frameworks. Svelte on the other hand has no such limitations just import the library and use it and it works as expected. So my current choices are sveltekit or astro

  • @neilterromn3432
    @neilterromn3432 Год назад

    lol, i thought you where fireship haha. Then i heard your voice and was like wtf? but ii liked the vid!!

  • @hakuna_matata_hakuna
    @hakuna_matata_hakuna Год назад

    you know what they say abpout the internet , say something wrong and you'll get detailed corrections , sometimes . it was nsane the way you ranked svelte reactivity on top of solidjs , bt ryan carniatto has live streams every Friday which I've found to be the most reliable source of detailed information about what these js frameworks are doing

    • @awesome-coding
      @awesome-coding  Год назад +1

      Thanks for mentioning Ryan's stream - I'll add it in my watchlist :)

    • @hakuna_matata_hakuna
      @hakuna_matata_hakuna Год назад

      @@awesome-coding he has some excellent ones , like one he did a few months after appDir release and brought out Excalidraw and laid out all the frameworks and where they sit on the server side optimization scales for like 4 hours , so educational. This was also a time where the react and vercel team messaging was very vague

    • @awesome-coding
      @awesome-coding  Год назад +1

      ​@@hakuna_matata_hakuna Thanks again!

  • @wezter96
    @wezter96 Год назад

    Have you tested out legend state?
    It enables more fine grained reactivity in React, Jack Herrington recently released a video about it :)

    • @awesome-coding
      @awesome-coding  Год назад +1

      Thanks for the suggestion!
      Didn't get the chance to look into that yet.

  • @grinsk3ks
    @grinsk3ks Год назад +1

    Pretty sure vue components don't rerun on change. Can you provide an example? Great Video all things considered.

    • @dolevgo8535
      @dolevgo8535 Год назад +1

      they rerender on prop changes, i assume that's what he meant

    • @awesome-coding
      @awesome-coding  Год назад +1

      Yep - my wording was not that great on this one.
      Here is a stack blitz (stackblitz.com/edit/vitejs-vite-aamf2c?file=README.md) showing the "re-render" when the button is clicked.

    • @grinsk3ks
      @grinsk3ks Год назад +1

      @@awesome-coding thx great demo

  • @iatheman
    @iatheman Год назад

    Great explanation. These are some amazing pieces of software.
    And they are too complex. The web front-end is already a mess, those frameworks and metaframewoeks, with their 10s of surrounding tools to add type-checking, linting, formatting, and all the concepts they bring like SSR, CSR, SSG, server node API vs Browser JS API, don’t do enough to fix the mess.
    So I will still avoid them on my projects for the sake of simplicity. Server-side gendering with some JS for reactivity gets most projects very far.

    • @awesome-coding
      @awesome-coding  Год назад

      If you are looking for something really simple give Solid JS a try :)

    • @iatheman
      @iatheman Год назад

      @@awesome-coding I will. Thanks for the suggestion.

  • @naolfekadu6101
    @naolfekadu6101 8 месяцев назад

    what about with svelte 5 and runes?

    • @awesome-coding
      @awesome-coding  8 месяцев назад

      Yep, Svelte 5 is switching to signals as well!

  • @ashleyfreebush
    @ashleyfreebush Год назад

    Misko called you out😅

  • @adambickford8720
    @adambickford8720 Год назад

    Angular/RxJs is solving a *much* harder problem: async reactivity. Simpler problems, like sync reactivity, can have simpler solutions.
    We can argue about the *need* for async reactivity, but if you actually have that problem, you're unlikely to find a more elegant solution than explicitly reified reactivity constrcuts ala RxJs.

  • @Danielo515
    @Danielo515 Год назад +1

    You what I always say? Fuck magic, gimme code I can read and modify

  • @rithtoo121
    @rithtoo121 Год назад

    Comment

  • @UwU-dx5hu
    @UwU-dx5hu Год назад

    Huh angular is for gigachads

  • @abujihadsalahudin
    @abujihadsalahudin Год назад

    With all due respect, who cares svelte, does it more intuitively easily that’s why Timmy’s belt is the number one framework by far I don’t care if under the hood one From Work, does it more efficiently

    • @awesome-coding
      @awesome-coding  Год назад

      Hey! Right - these details don't really matter for the end developer.
      However, these decisions have implication when it comes to performance, hydration and other optimisations, so, one way or another, we are all affected by it.

  • @shift-happens
    @shift-happens Год назад +1

    May I ask, where your awesome accent comes from? Love your videos! Greetings from Bulgaria :)

    • @awesome-coding
      @awesome-coding  Год назад +6

      Are you implying I'm not sounding like a native speaker?! 🥲😂
      I'm from Romania ✌️

    • @johnforeverrules
      @johnforeverrules Год назад

      @@awesome-coding I also like the way you speak. your videos are awesome. God bless

    • @awesome-coding
      @awesome-coding  Год назад

      @@johnforeverrules Thank you!