Components
Components are basic building blocks of Qwik Applications. Qwik components are unique in that:
- Qwik components automatically get broken down into lazy-loaded chunks by the Optimizer. (See Optimizer discussion)
- Are resumable. (A component can get created on a server and continue its execution on the client.) (See resumable discussion)
- Can render independently of other components on the page. (See rendering discussion)
component$
Qwik components are declared with component$
API.
const Counter = component$((props: { step?: number; initial?: number }) => {
const store = useStore({ count: props.initial || 0 });
return <button onClick$={() => (store.count += props.step || 1)}>{store.count}</button>;
});
NOTE:
- For an explanation of
$
see lazy-loading and Optimizer discussion. - For a detailed discussion of props, see Component/props discussion.
Using components
Qwik components can use other components.
const Counter = component$((props: {step?:number, initial?: number}) => {
...
});
const MyApp = component$(() => {
return (
<>
<div>Single: <Counter /></div>
<div>Dozens: <Counter step={12}/></div>
</>
);
});
The above example shows how the MyApp
component can use the Counter
component. The second example shows how one can use binding to pass values to the Counter
component's props.
Re-rendering on Reactivity
Qwik components are reactive on the component level. Component props, as well as stores, are proxies. These proxies track reads as well as writes.
- A proxy-read during OnRender function execution lets Qwik know that the OnRender function depends on a given property. A read creates a subscription on that property. In our example, OnRender reads
{store.count}
, which creates a subscription that tells Qwik that whenever thestore.count
changes, the component should be invalidated. - A proxy-write notifies Qwik that all associated subscriptions should be invalidated.
When components get invalidated, they are added to the invalidation queue, which is flushed (rendered) on the next requestAnimationFrame
. This acts as a form of coalescing for component rendering.
For a detailed discussion of reactivity, see related discussion.