Handling register()
in Qwik: Use Inside useVisibleTask$
for Better Performance
When using Qwik (especially in combination with @builder.io/sdk-qwik
), you may run into an issue when you try to call register()
outside of useVisibleTask$()
in the module scope. This is similar to how React allows you to invoke certain functions at the module level.
However, in Qwik, this approach doesn’t work as expected. You must wrap the register()
call inside useVisibleTask$()
instead. The reason is that Qwik avoids running component code in the browser unless it is explicitly instructed to do so. Adding the register()
call inside of the useVisibleTask$()
instructs Qwik to run it in the browser, which is necessary for it to work properly.
Here’s a working example:
import { component$, useVisibleTask$ } from '@builder.io/qwik';
import { routeLoader$ } from '@builder.io/qwik-city';
import {
Content,
fetchOneEntry,
getBuilderSearchParams,
register,
} from '@builder.io/sdk-qwik';
const Counter = component$(() => {
return <div>Counter</div>;
});
const customComponents = [
{
name: 'Counter',
component: Counter,
},
];
export default component$(() => {
const content = /**/
useVisibleTask$(() => {
register('insertMenu', {
name: 'Our special components',
items: [{ name: 'Counter' }],
});
});
return (
<Content
model={BUILDER_MODEL}
content={content.value}
apiKey={BUILDER_PUBLIC_API_KEY}
customComponents={customComponents}
/>
);
});
Thanks,