The Svelte 5 Guide: Runes And Universal Reactivity

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
SW is a language that takes your component code and turns it into efficient JavaScript code in 2019 swell challenged what reactivity could be in a JavaScript framework by moving the reactivity from the component API into the language itself spel free moves reactivity out of the component API and into the language and if you're already a user of Swell this might look really familiar so in sell 3 we can create our reactive value by declaring let count equal Z and then we can create a the right value by saying dollar sign colon double equals count * 2 and then we can use assignment or reactive updates and then double is going to update each time since count is a dependency but this is not without its problems and you might run into weird issues if you don't understand how reactivity in swell 3 works so let's see what happens if we console count and double inside of the increment function you're going to see the double is out of sync and why is that well because the dollar sign colon line isn't going to run until the next D update to make sure that all of the updates are in place and web pages are basically firstperson scrollers and you want that batter is moved 60 frames per second so you want to do all of your logic at the JavaScript part then you want to do Styles layout paint and compositing and then we can see that this is true by requesting the next animation frame in the browser so on the next sck we're going to log count and double and they should be in sync and this sort of gotas is what SW 5 is trying to improve on so we can actually see how reactivity in swel 3 works by looking at the compiled output of dollar sign double equals count * 2 we can actually see that SW created this update function which has this invalidate function you don't really have to understand how the code works but we can actually see that for example if we try to move the count value inside of the double count function our reactivity breaks because the compiler can see the value it can't reach inside of the function to update it and if you look at the output we can see that invalidate only runs once and it's never going to rerun again to fix this issue we can pass count as a dependency and the swell compiler is going to see it and now the same as before now we created an update function with an invalidate function inside of it which is going to rerun each time and this is another GOA that can get you if you don't understand how swell Free Works let's talk about another gotcha let's say that you want to refactor your logic inside of a create counter component well count is now no longer reactive because this has no special meaning inside of a function and dollar sign column has no special meaning also which might surprise you and to solve this problem swel introduced stores which are really just writable objects you can use inside of swell components and regular javascrip files to have the same reactivity so you can see we can just create counter we can import the writeable we can destructure subscribe update and then we can provide an inrent function and return the Subscribe and increment method to create a custom store contract and stores are great but this is just one more thing that you have to learn and know about and now we can use the store inside of our components so we can subscribe for it and it returns an unsubscribe method which we can invoke inside when we unmount the component but as you can see this is a bit verbose that we have to do this so swel introduced another syntax sugar which is dollar sign so we can see that we can say cons count equals create counter and then we can use the synthetic sugar dollar sign count and this is going to dis sugar into the Subscribe and unsubscribe method for us but there is another gocha that this syntax only works inside of dot swell components so now this is another thing that you have to understand and when none of these things are a deal breaker things could be a lot more cleaner swelt introduces a new reactive system runes runes are a universal fine grain reactive system reducing complexity and making swell smaller faster and more consistent and a rune is a letter or Mark used as a mystical or magic symbol so let's look at state in SW five here I have a simple count and in this component this callede might look familiar I just have an increment function and I have a count here but in Cell 5 to declare a piece of reactive State you have to use the dollar sign State Rune and next we can create a the right value double by using the dollar sign the Rune and now you can pass an expression inside of it such as count time two and now this code is going to work the same as before and the output is more predictable because SW uses signals under the hood and now we can see that count and tble are in sync and everything works a lot more predictably let's talk about side effects side effects are where you can run your code where you can talk to things outside of your component such as the browser API fetch for example or manipulating the Dom so here in this example we can use the dollar sign effect Rune and inside of here where we say console.log count swelt is going to see that count is a dependency of the effect and is going to rerun each time count updates as you can see there are no dependency arrays because spelt uses signals under the hood everything works automatically n effects are also a place where you can run your code when the component mounts and you should rarely reach for effects unless you're doing one of those things so let's look at another example here I have some count State and milliseconds and inside of this effect we can see that effects rerun whenever their dependency change here I have con interval equals set interval and then we can see that we have count and milles here which are going to be treated as a dependency of this effect and then we can also optionally provide a callback which is going to rerun each time before the effect updates and when the component unmounts and in this example we just have a simple interval which you're going to make slower or faster and you're going to see that it works beautifully and now we're going to see is going to be half the speed and everything works great and now we can also save faster and return it back to Baseline and now we can see wherever these dependencies update before the effect rerun is going to run this call back and when the component unmounts is also going to run that code but one thing that you shouldn't do with the effects is using them to derive state or synchronized State and that is why you're going to really reach for effects because there's simply no reason to since you have the state Rune and the dollar sign derived Rune so in this example I have a count and double and you might be tempted to do something like this but don't do it so I'm reassigning double equals count * 2 and now inside of increment you're going to actually run into the same problem that we've seen before count and double are going to be out of sync because effects always run before the next Dome update so you shouldn't use effects to derive values and you should instead use the dollar sign derived Rune beautiful runes are just function like symbols that provide instructions to the swell compiler for example you might be tempted to think that these runes are functions but they're just instructions to the swell compiler as you can see there are no Imports and another benefit is that they're easy to type because they look look like functions so when it comes to your tooling this might just as well be regular functions but as you can see we can look at the compiled output which is surprisingly simple to read so let's look at the state Rune which gets converted into a signal so first we're importing everything from this dollar sign UT so you can say dollar sign do source which is basically just a signal you can also see that the right Rune gets turned into a derived signal so this is just another signal that has count as a dependency and we can also see that swell differential between user effects and the template effects so user effects are the effects that we defined ourselves so you can see here is console.log and this is very easy to read this just gets the most recent value of count and you can see here are the template effects from a template in the swell component we can see it uses a special function to set a text and it says the text what it should be with the freshest value of count and this is a huge reason why spell 5 is smaller faster and more efficient so what is univ ival reactivity Universal reactivity means that you can use the same logic inside and outside swell components so here I have a simple count example and now like before now we can encapsulate this logic inside of a create counter function and then we can return the count but there is going to be one problem spell doesn't change how JavaScript works for example if we try to use count inside of this component we can initialize it by saying let counter equals create counter and now when we log do count we're going to see it's zero as expected but now when we increment the value of count we're going to see the next time is zero and that's because that's just how JavaScript Works reactivity in this case can't magically cross the function boundary so what we actually can do is use a getter and Setter but we can also just use a regular jav stre function so in this case we can say get count and we can return the count value and we can also set the count value we can accept the value and then we can set count to the new value and now in this example when we def find the counter again and we say do count is going to be zero now we're going to increment the count and then when we say do count again is going to be one and we can actually see if we try to refactor this function into a separate file this can be a swjs or swell. DS file and now when we have this here we can just import the create counter from counter. swell. JS or TS if you're using T script and you can see it works beautifully now we can say counter. count plus equals 1 to increment it and is going to update where we have counter. count thanks to the magic of signals inside the dollar sign stay tune swell WS objects and arrays with proxies which intercept reads and rights of objects and array properties and turns them into signals and what does this exactly mean well let's look at some examples of deeply nested reactivity if you remember this example from before here we Define a count with saying count equals sign state zero and then we have to define a getter and Setter now when we say counter. count plus equal 1 we're going to invoke the setter and update the count value which is going to reactively update in our template where we have counter. count but what I haven't told you is you can write this in a simpler way so instead of having to define a getter and Setter you can use deeply nested reactivity by using an object in this example so we can turn count into counter which has an object with a count on it which is zero and this uses a proxy under the code so you don't have to specify a getter and Setter yourself and now everything works the same as before and why is this actually important well let's look at how you would write code if you didn't have deeply nested re activity in this case I have a simple to-do example where I have this to do array and let's say that we don't have deeply necess activity we'll have to create a done and text signal and then it wouldn't be enough just to push this if you want it to be truly reactive we do have to specify a getter and Setter for each of the field and this is a lot of boiler plate so SW introduce deeply nested reactivity you don't have to do any of this this is how you do it in swell five since we Define an array it's already deeply reactive and now the only thing that you have to do is push the done and text values and under the hood to is a proxy that still uses signals and SW is going to turn the properties on the objects into signals and now you can simply bind the value of the to-do text and you can also easily bind if the to-do is done another benefit of necessary activity is if you're for example storing your reactive value somewhere in local storage or a database now when you return them you don't have to reunify them or do anything else when you reassign them to state they're going to be deeply reactive also alternatively you can use a class because spelt makes classes cool again so if you feel in classy if you have a class here you can define a done and text fields and SW is automatically going to turn them into Getters and Setters for you so now this greatly improves the experience of using classes in swell 5 let's look at some other benefits of deeply nested reactivity thanks to deeply nested reactivity you don't need reactive assignments for objects and arrays so here I have some numbers and then I'm going to calculate the total by using a the ride Rune and I'm going to just reduce the total sum but that's really not important but it's important how we update this value so in the past if you're using an older version of SW you might remember something like this to update the value reactively we had to reassign it and then we would have to spread the value and then add the new value but this is no longer the case in SW 5 because of deeply nested reactivity you can just straight up use array methods like push so we can say numbers do push numbers. length plus one and this works as expected let's talk about shared State because of deeply necessary reactivity you can have shared State across modules so you can export let preferences equals dollar sign State and here you can have an options object or whatever else you want example I'm going to set a tee to dark and now when you update it this is going to reflect in your components so now we can look at preferences. te if it's light then we're going to show one of these emojis spelt also provides proxy map set date and URL classes which have the same API as their non-reactive counterparts and this is really cool in this example ex Le we can look at some reactive Imports so here I'm importing URL from sw/ reactivity then we can actually construct a new URL and then we can pass it some URL and now we can bind these values to it and this works as the regular API so now when we update host name it's going to reactively update and same with the path name so this is deeply nested reactive state in S 5 well there are some surface level similarities with swel 5's API to react swel 5 is nothing like react and is more inspired by its contemporary Frameworks like solid JS and View and what's really important to understand in swell 5 are the reactivity patterns and that runes are just reactive Primitives so you can use deeply nested reactivity or a class to avoid boiler plate but runes arejust reactive Primitives which can be used to make a reactivity system let's look at some of the examples maybe you're a fan of solid so we can create this use signal function passing the initial value we can create a value signal and pass it the initial value and then we can create a read and write function and we can return the read and write functions and now we can use this API we can say let count set count equals U signal which we D structured using array dest structuring and now we can use this the same as solid and solid is actually closer to swell because they both use signals maybe you're a fan of you so you can create this function ref passing the initial value we can create a value signal with the initial value and now instead of returning a function inside of a tuple we can return a getter and a Setter and now we can say let count equals ref we can pass in the initial value and now we can use it the same as before and of course this is completely up to you what do you want to use but it's really important to understand what runes runes aren't some marketing gimmicks in an attempt to Rebrand signals because as You' seen runes are just function like symbols that give instructions to the swell compiler which then get turned into signals under the hood let's talk about props in this example I want to create a simple reusable button. swell component the first thing I want to do is get children which I can do using the dollar sign props Rune now I can destructure children from the props object and I can render them to the Dom another prop I want to include is a class but a class is a reserved keyword in JavaScript so we can just rename it and lastly let's also spread the other props we want to include and this looks great to me and now inside of our component we can import button we can for example create a count signal and then we can pass it as a child to button this works great and let's also pass an event listener so we can say onclick and we can just increment the count and notice another thing in spelt 5 is is that event listeners are just regular properties which mean that you can pass them easily and even spread them props are read only by default though unless you're explicit and make them bindable since state is deeply reactive and this just means that you can change some State upwards in your parent from a child on accident so let's look at an example so here I'm importing this mouse component and then I'm going to set the coordinates here and output it on the screen and here is the mouse component itself so we can just pass the coordinates as a prop and then we can reassign the coordinates as you can see because state is deeply reactive we can by accident change the state in the parent and that is why this is read only by default and of course the first thing you can do we can dra pass chords as a regular prop to the mouse component and you're going to see we're just going to change the X and Y of the mouse in the mouse component itself and this is great but what if you want to bind the value in the parent and change the Cor itself well we can just make the cords bindable using the dollar sign bindable Rune and that's it and now we can change Mouse we can bind the value of chords and now it's going to work and now we're going to see the value is going to update in both components beautiful we can also set a default value or coordinates inside of bindable so you can pass whatever you want as a fallback value if you don't pass the prop under the hood SW uses get set methods for props and the text if you're using a set method on a readon prop we can look at the output so here is how it looks like components are function so we have this mouse function that accepts a note and then we have this read only property get CES which is the default and then swell can check hey if this is writable okay then everything is fine otherwise it's going to throw an error with the useful message informing you that you should make it bind theable if you want props are more simpler and more powerful than before let's talk about inspecting State being able to debug values and see how and why the change is really important during development we've seen in a previous example that we can use an effect to log the value of count when it updates but this is ver both and instead of using an effect for this you should use the dollar sign in spectrun by default once you pass it a signal is going to use console log by default so whenever this value updates is going to get logged but you're not only limited to console.log you can provide your own custom callback using wi this is going to accept a type and you can also pass it the parameter what you pass to inspect in this example this is count and then you can also check what type it is in this case if it's type update you can open the debugger or you can do a stack Trace that is completely up to you as we can see in the next example you can just simply pass console. trace and another benefit of using the inspect run in swell 5 is that it only works in development so you're not going to accidentally ship it in production and how beautiful is that friends swel 5 not only enables a better developer experience for the average developer but also for Library offers and maintainers and that is why we're already starting to see some awesome projects in the swell ecosystem so for example here we have this awesome project Rune which has a bunch of useful utility functions for SW 5 here we can look at this watch utility which watches for changes and runs a call back and we didn't talk about some more advanced aspects of effects because they're really not important for this video but for example sell provides an untracked function allowing you to specify that the dependency shouldn't be tracked and this watch utility basically you just pass a signal in and then when that signal updates it can run some call back for you and this is all possible because F 5 is smaller faster easier to use and more capable than before with runes spelt becomes a much simpler framework you don't need to understand the special let Behavior you don't need to understand the dollar label you don't need to understand how export works you don't need to switch mental modes between spelt and nonel JavaScript you probably won't need to use stores or life cycle functions and so when people come to our community in future they're going to have a much easier time getting comfortable I think if anything I'm more excited about what this means for people who are already maintaining able spel Cod bases we've spent a lot of time converting existing apps and libraries to see how it feels and it really does feel good thank you for watching
Info
Channel: Joy of Code
Views: 17,955
Rating: undefined out of 5
Keywords: sveltekit, svelte, runes
Id: tErKyuUTzsM
Channel Id: undefined
Length: 21min 40sec (1300 seconds)
Published: Fri Jun 21 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.