Syntax Video
Should You Use Signals with React?
- 0:00 intro
- 0:56 useState Example
- 1:39 useState re-renders
- 2:45 how react data flows
- 3:54 @preact/signals-react Example
- 4:47 fine-grained reactivity
- 5:37 @preact/signals-react code walkthrough
- 8:03 React Compiler Example
- 9:23 Signals for global state management
- 10:43 Signals Proposal
- 13:09 use-signals hook + polyfill
- 14:59 signals from scratch
- 18:17 how to use signals in React today
- 18:44 thanks!
intro
what's up CJ here in this video we're going to talk about signals and specifically in the context of react and so first we're going to talk about how react Works in terms of unidirectional data flow and then we'll show how signals can enable fine grained updates and how that can potentially increase the performance of your apps and potentially reduce complexity and make State a little bit more manageable inside of your react apps now another aspect of this is the signals proposal that's been brought to the tc39 to potentially add signal to the web browser So today we're going to talk about how react Works without signals how you can add signals to your react app today we'll talk about the proposal what it means we'll look at some experimental implementations and we'll also compare it to Output of the react compiler which is another effort to potentially try and optimize your react apps so if that sounds good to you let's dive in my name is CJ welcome to [Music] syntax first let's take a look at an example that is just using UST state
useState Example
with re so for this app I have an input where I can type my name and then if I want it to update below I can click set name and that sets the value there if we look at the code it's pretty straightforward we have a use State here that is keeping track of the input value and then another use State that'll keep track of the name once we click that set name button and so we have the value set on the input here we update that input value anytime it changes and then when the button is clicked we actually call set name with the current value of the input and then that name is pass down to this greeting component and the greeting component just has some simple logic if the name has a value it's going to display it if it doesn't have a value it's going to say name not set pretty simple but what we want to look at here is how often these components render so right now I have console logs anytime these components re-render but we can also enable in the react Dev tools this option here to highlight updates when the components render so we'll see on the page any component that renders is
useState re-renders
going to be outlined and so check this out as I start to type we can see that the app renders and the greeting component renders and that's on every single key press and if you're familiar with how react works this makes sense because on every single key press we are setting that input value which changes the state and when the state changes everything has to render including children and what's interesting about this is even though greeting doesn't even care about input value it only cares about name it still has to render by default and that's just the way react works when State changes a component will render and every child in the subtree will render unless you're using something like use memo or you've memoized the component and to see this in a diagram it's fairly simple right so we our app has some state it has that input value State and that name state but anytime that state is updated this entire tree which starts at the app and then goes
how react data flows
down to the greeting component will need to rerender and it's important to note a render in the context of react doesn't mean every single element on the page is getting replaced with the same value that is the job of the virtual Dom right so a rerender means we create a new virtual Dom tree that then is going to get diffed against the previous virtual Dom tree um so while it does render a lot it's still fairly performant for most use cases right um but one of the things about this is once you start dealing with less trivial examples where you have lots of state and lots of components all over your app you could start to run into performance issues because you're getting potentially too many rerenders and maybe you've never used use memo or or memo for a component to prevent it from rendering you could potentially run into some issues with your app running slow and so react has a top- down data flow right so we Define our state here and then that flows down throughout our app and so this is a unidirectional data flow and that's why we get these re-renders in this way now
@preact/signals-react Example
let's check out an example with signals and so for this example I'm actually using the preact signals react Library so this is a library from the preact library that lets you use signals directly inside of your react app you don't need to use preact and so I have that set up in this app here and it's going to work in exactly the same way I can type I can click the button it updates but let's take a look at the amount of rendering that happens so I'll type here and you'll notice that the only thing rendering is this input element which I've wrapped in its own component here to get the benefits of signals but you'll notice as I type the whole tree is not updating the only thing that needs to update is whatever is dependent on that specific signal and then when I click set name the only thing that's going to update is the thing that's dependent on the value of the name and for me this is really one of the main benefits of signals now there are other benefits but one of the
fine-grained reactivity
main things about signals is this idea of fine grained reactivity if we contrast with our current diagram this idea of signals so our app now uses signals instead of State variables and anytime one of those signals is changed the only things that render are the things that actually reference the value so in this case we have our signal input component which is dependent on input value so if input value changes this is going to be the only thing that renders not the whole tree and then greeting is dependent on name and so if name changes greeting is going to be the only thing that reenders and this is known as fine grained reactive essentially the specific spots in your app that access these signals are going to be the only things that need to render not the entire tree now let's take a look at the code for the with signals example now in this case like I said I brought in signals react and we're bringing in the signal type and then also this use signal hook so if we take a look at the app it's not much different instead of use State we're now
@preact/signals-react code walkthrough
just calling use signal the other parts are mostly the same you can see whenever we click set name we're setting signal. value so this is how you update a signal is you uh modify the dot value property on it and then the other thing we've done is we're actually passing these signals around so we have this greeting component here I've defined its prop so that it takes in a signal that is a string so we're actually passing that signal directly down to it and then here in its render function it can just use the signal directly now the one major difference you can see here is I've actually extracted out that input into its own separate component called a signal input and the main reason I did that is because that input is dependent on the input value and I wanted it to have its own render tree so that way if input value changes only it renders not the entire app component and so if we take a look at signal input it's essentially just a wrapper around an input but it allows us to pass in that signal value here and then also automatically will set the signal value for us so it's kind of a Helper and that it automatically does these two things
but the main reason I wrote the code in this way is because of this right here and so essentially anywhere in your application where you access the value of a signal that is a specific spot that can be optimized to only render that one specific spot and so if I would have defined this code this input inside of the app component here that input isn't its own separate component so if its dependencies change everything around it would have to rerender to now the other aspect here is you'll notice that right here when I'm referencing the signal inside of my jsx I'm not using value and this is another nicity that you can get when you're using the transform provided by the preact signals react Library where essentially it can detect if you're referencing a signal inside of your jsx it can recognize that and essentially turn this into its own text node that can be directly accessed and modified under the hood during these renders and so in the context of react the main benefit I see of signals is this idea of fine grain reactivity
versus rendering an entire tree if just one thing changes even if your your sub trees don't change now you might be wondering okay well we can use react and we what if we did use use memo to memorize a component or use memo to memorize some State and for that I've actually set up the same example but using the react compiler so here's the example with the react compiler works in the same way I can type my name click the button update it but let's look at what's happening here so when the page first loads the app renders and of course the greeting component renders but as I type into the input take a look at that the react compiler has optimized the greeting component here because it knows that greeting isn't dependent on the input value it's only dependent on on name and name isn't changing until I click this button so when I click this button finally greeting will render and so that's what's nice about the react compiler is you'll get some of these things for free but you'll notice that even when I'm typing in the input the app still has to render right we've optimized the fact that greeting doesn't
React Compiler Example
have to render every time but the overall app component does have to render because we have to start at the top of the tree to determine what should be rendered and whenever you memorize a component that's actually another operation that's happening behind the scenes it's it's it basically comparing its props previous value and next value and if they haven't changed then it won't run the render at all so it's slightly more optimized but you're still going to get a lot of reenders that you didn't necessarily expect it's not exactly fine grain updates like you get with signals it's just a little bit smarter about when certain components should R render now fine grain reactivity is just one of the benefits of signals the other benefit I see is that these signals don't have to adhere to the rules of hooks so in this example I am using their Ed signal hook that they' provided for us to define a signal locally to a component but I also could actually Define these outside of the component and the app would still work in the same way so I'll do this uh now
Signals for global state management
we can't use U signal because U signal is a hook it's meant to be used inside of components but I can just directly Define a signal and so now with these signals defined outside of the component the app will actually still behave in exactly the same way so if we head over here and then we test this out but this has a lot more implications right because what if we just Define this in a separate module well now we instantly have a global State Management solution right we could we could Define a module that has a few signals inside of it a few updater methods now we don't need to reach for other State Management libraries we can just use the signals themselves and because of that very reason right if we have this idea of signals and they can be not tied to a component right it's just a way of working with State and then then our framework for actually rendering out these components knows how to integrate with those signals in order to update in the right way that leads us to a bigger idea which is what if signals were just built into JavaScript and so this is the JavaScript signals standard proposal
Signals Proposal
it's currently stage one it's being considered by the tc39 committee but they have some ideas here that basically say what if signals were something just built into JavaScript and they ruce this top level API so capital signal. state capital signal. computed and they essentially argue that because so many front end Frameworks are already introducing their own library for signals it would potentially increase performance and also standardize things if there was some primitive in the browser that actually gave us this reactive ability with signals and I haven't talked about this yet but react is essentially one of the only front end Frameworks that has not really started to adopt this idea of signal right every single other framework out there is either considering it or already using them so view felt solid Ember angular all of these Frameworks are already using signals internally they each have their own implementation but they're all using the same
underlying idea of having these pieces of state that can essentially automatically update specific areas and also track any of their dependencies automatically to know when things have changed so definitely check out this proposal but part of this proposal is the fact that they've introduced a polyfill and so this polyfill will let you use capital S signals today you don't have to wait for it to be standardized and eventually if you want to keep using it and maybe it's only supported in certain browsers you could still bring in that polyfill and then eventually if it does move to stage four and get adopted into the language you wouldn't need to bring in that polyfill anymore once it's supported across all runtimes and browsers but this allows you to give it a try today and also play around with the proposed API right so this is one of the ideas of a proposal is they're suggesting well we believe that signal. state should exist and signal. computed should exist and this is the way that it's going to work but that could still change right and so if you read through the proposal if you
give the polyfill a try you can start to form your own opinions of do you like this API does it make sense to exist inside of JavaScript and join the discussion so if you take a look at the proposal signals repo there are a bunch of issues of people talking about what they like what they don't like what should be considered instead and so because this is still a stage one proposal there's still time there's still time to have a conversation about um what should be added to the JavaScript language or what you like about it or what you don't and that brings us to the idea of something like use signal so this is an experimental library from daishi they're the same people that work on joai and zand and essentially this is a hook that is built around the signal polyfill and allows you to use signals inside of your react app so I've created the exact same example and now now you can see it behaves in the same way as I'm typing in the input that's the only element that's being updated and then when I set the name that element gets updated directly and it's not rendering the whole tree and so what's interesting about this
use-signals hook + polyfill
approach is this is potentially looking into the future right because if something like capital S signal existed inside of the browser first of all this Library would get very much smaller the only code that would be needed for this library is integrating those standardized signals into react versus having to bring in the polyfill as well um and so this is just a glimpse of what could happen if something like capital S signal existed in the browser essentially all of these Frameworks that are doing these signall like things could remove a bunch of code use the underlying standard and then just integrate it with their framework now to use this particular package it's a little bit tricky because you have to change the jsx import source so here in my ts config I have the jsx import source as U signals and whenever I want to reference refence a signal I have to use this dollar sign that comes from the U signals library and essentially this is a marker that says this is the one spot that needs to be updated if this
value changes and similarly I'm I'm adding it here when I'm accessing name and essentially this combined with the jsx transform when our code is getting transpiled into actual JavaScript code the custom jsx transform that's provided here knows to insert some specific code that says hey only update this specific element if the signal has changed so signals seem great but some of the magic here that you might be wondering is how can a signal keep track of its dependencies automatically and this blog post that was written by Ryan carniato called building a reactive library from scratch basically shows a simple signal implementation from scratch and you can kind of get an idea of what's Happening Here and so the hook that they've created here is called create signal it essentially just returns two things the value and then a function that can set that value and this is just using the IDE of scope en closures inside of JavaScript where we now have a function that'll return the value and we have a function that will set the value so
signals from scratch
that's the basics of a signal and and this is more of the like a react style Ed state but each one of these is a getter and a Setter function instead of just being the state value in a Setter function from there now we can actually talk about tracking subscriptions and tracking who has access to these various variables one of the key Concepts here is this context array and so right here you can see that anytime the value is red so this would be like signal. get or in this case we're just invoking that signal to get the value anytime it's red we can find what context it's running inside of whether that's an effect or anything else that might be accessing a signal and we can store that and if it's running inside of an effect we can then add it to our list of subscriptions and so this is the piece of signals that actually is Pub sub essentially we have a publisher and then a list of subscribers so any bit of code that reads from a signal whe whether inside of a computed or an effect is going to get put into this list of subscriptions and then later on anytime we update our
signal we can then iterate over that list of subscriptions and then alert the computed value or alert the effect that something has occurred and from there we have this idea of an effect so we can pass this callback function here and the way that this is set up is the moment that function is called so when you define a computed or when you define a function that should be in effect it gets passed in here and we're going to call execute and then when that happens we can take our current effect and everything that's related to it and then push it into the list of things that are running and so if we look back at before if something is running whenever a value is read that's when it's added to the subscriptions and so that essentially creates this relationship of you define your computed or your effect it starts to access signals and then anytime it accesses a signal that calls the read function we know what the current context is because we're executing inside of a computed or executing inside of a effect and then we can add it to the list of subscribers and so on paper signals are actually very simple the the idea themselves but what gets a bit more
complex is the optimizations and how can you make sure that this runs efficiently and potentially might prevent uh uh dependency Cycles if those exist or might actually be more efficient about deciding which dep dependencies to update in which order so there's a lot more that can actually go into the underlying signal imp implementation to make it more performant and that is is one of the intentions of The Proposal signals standard where they're looking at here performance and memory usage because if you can offload some of this dependency tracking and alerting of subscribers to native code which is what will happen if it gets added to the standard then you can expect that all of your apps are just going to get a whole lot faster especially if they're using the standard so that's it for this video if you want to take a look at the code click the link in the description it's all there for you to check out if you want to start using signals in react today the recommended option is to use prea signals they've figured things out they've done a ton of optimization it's definitely the way to go if you want to use it now if you want to Future proof
how to use signals in React today
your code you could potentially try to use something like D's use signal but this is experimental especially because it's built on top of the experimental polyfill itself so let me know in the comments what do you think do you think re this should be something built into the browser do you think this is how we should be building react applications let me know I hope you enjoyed this one and I'll see you in the next one [Music]
thanks!
Quote it with credit and a link. Quoting Syntax