Fine-Grained Reactivity (Signals) in Qwik
Qwik (the JavaScript UI framework) uses signals for reactivity, meaning it should only re-render the DOM elements that directly depend on reactive state rather than the entire component that uses said state.
However, consider the following example of conditional rendering:
In this case, Qwik should only re-render the contents of the
<div>
when show
is updated. I don't understand, however, how Qwik knows what to re-render in this case. Even is show.value
is behind a Proxy
, there's no way for it to know specifically which element it's being accessed in.
If this code was running in React, React could know that show
is being accessed in the component, but would re-render the entire component. If you were to write this code in Solid (another signals-based framework), you would use the custom <Show>
component to tell Solid a signal is being used.
How does Qwik know to re-render only the <div>
's contents and not the entire component when the signal is being used in a ternary outside of Qwik's knowledge? Is it just bundler magic, an obscure JavaScript feature, or am I missing something obvious?1 Reply
I found an article that mentions Qwik using Dynamic Tree Shaking, where a Rust-based compiler discards unecessary code. Does the Rust compiler also identify where reactive state is used? The article does say the compiler also "also identifies which bits of code are only called in the initial render and which are required for additional interactivity", but I don't know if that's referring to what I'm talking about.
Looks like it is Qwik's Rust compiler after all (which they call the Optimizer). They specifically say "The Optimizer extracts expressions (usually functions) into new files and leaves behind a QRL pointing to the lazy-loaded location", and I'm guessing that also helps Qwik know what to re-render.