iTranslated by AI
Can Qwik/QwikCity, the 'Theoretically Strongest' Framework, Become a Common Frontend Infrastructure?
I was thinking about whether Qwik could be used as a micro-frontend foundation and came up with various ideas. I created several things as byproducts.
tl;dr
- Qwik is theoretically the strongest. But it is difficult.
- By using qwik-react, you can selectively switch between Qwik and React, so it seems usable as a meta-framework similar to Astro.
- Other frameworks should also be supported if you are determined => I implemented qwik-svelte and qwik-vue.
- The ultimate issue is whether Qwik will become popular.
What is Qwik/QwikCity?
Qwik is an SSR-first UI library that generates components from a React dialect of .tsx.
import { component$, useSignal } from '@builder.io/qwik';
export default component$(() => {
return (
<>
<p>Parent Text</p>
<Child />
<Counter />
</>
);
});
const Child = component$(() => {
return <p>Child Text</p>;
});
const Couter = component$(() => {
const counter = useSignal(0);
return <button type="button" onClick$={() => { counter.value++ }}>{counter.value}</button>;
});
QwikCity is the framework for Qwik, corresponding to Next.js or Remix for React. As features provided as a framework, it includes the popular File-based routing and server actions during routing.
Example of File-based Routing
src/
└── routes/
├── contact/
│ └── index.mdx # https://example.com/contact
├── about/
│ └── index.md # https://example.com/about
├── docs/
│ └── [id]/
│ └── index.ts # https://example.com/docs/1234
│ # https://example.com/docs/anything
├── [...catchall]/
│ └── index.tsx # https://example.com/anything/else/that/didnt/match
│
└── layout.tsx # This layout is used for all pages
Example of server actions
import { component$ } from '@builder.io/qwik';
import { routeLoader$ } from '@builder.io/qwik-city';
export const useProductDetails = routeLoader$(async (requestEvent) => {
// This code runs only on the server, after every navigation
const res = await fetch(`https://.../products/${requestEvent.params.productId}`);
const product = await res.json();
return product as Product;
});
export default component$(() => {
// In order to access the `routeLoader$` data within a Qwik Component, you need to call the hook.
const signal = useProductDetails(); // Readonly<Signal<Product>>
return <p>Product name: {signal.value.product.name}</p>;
});
Since it is one of the standard templates for @vitejs/app, you can get started simply by choosing Qwik / QwikCity with npm create @vitejs/app my-project-dir.
The "Theoretically Strongest" Feel of Qwik and its Difficulty
I believe this kind of idea arises as a result of the declarative UI paradigm born from React reaching its logical conclusion.
"If declarative UI can be realized—meaning if you can get the same output for the same component declaration and its input—then the implementation can be anything."
Consequently, the internal algorithm doesn't need to be a Virtual DOM; it just needs to provide an API that looks that way to the user.
Qwik is like a "Jiro-style" (massively stacked) framework with all modern frontend optimization techniques maxed out. It pushes Svelte's compile-time optimization and Astro's islands architecture even further, with the API system organized around the premise of hydration at the function level. By assuming SSR, most processing is done at compile time, removing unnecessary parts from the client except during SSR, and then selectively loading only what's needed in response to browser events. The resulting finely divided chunks are aggressively prefetched by a ServiceWorker.
It is probably difficult to achieve more optimization than Qwik with modern web technology. I read the internal implementation during my investigation and felt a sense of madness, like "I understand what you want to do, but did you really implement this? This?"
However, to realize that ideal, you need to write code under strong constraints, which is difficult for humans to handle. For example, if you write code thinking it's React, it will fail as follows:
export const MyApp = component$(()=>{
const signal = useSignal(0);
const onClick = () => {
signal.value++;
console.log('clicked')
};
return <button type="button" onClick$={onClick}>ClickMe</button>
});
(A build error will appear, for now)
This works if you write it like this:
export const MyApp = component$(()=>{
const signal = useSignal(0);
return <button type="button" onClick$={() => {
signal.value++;
console.log('clicked')
}}>ClickMe</button>
});
On the surface, it looks like a minor change, but to make this change, you need to think like the compiler.
- Calls to APIs ending in
$have their arguments converted to a URL format calledQRLwithin Qwik, andonClick$embeds the QRL path as anon:clickattribute. - When the click event of an
on:clickelement is fired, the QRL is resolved by the core qwikloader, and the corresponding JS chunk is loaded and executed. For this purpose, the callback is emitted as a chunk during build. - Unlike React, the function scope is called only once, and callback functions called via QRL cannot access the parent scope unless they go through the QRL.
- Props to components must be passed as JSON-serializable objects or as QRLs.
...I learned various things like this while writing Qwik, but it's certainly not something you can use with React knowledge alone. You need to align yourself with the feelings of the Qwik Optimizer—or rather, you need to write code as if you were the compiler itself.
Regarding what specifically needs to be learned, the chapter labeled "Advanced" in the official documentation seemed almost mandatory to visualize the internal logic. At least I ended up reading almost every page (partly because I was building a library).
To use it practically, you need to be able to visualize the passing of QRLs and reference resolution by qwikloader.
When Can Qwik Be Used?
My initial concern was, "If it doesn't load until I click, won't the response be poor in environments with slow mobile networks?"
However, when I actually checked the behavior, QwikCity preloads fragmented chunks with its built-in ServiceWorker, so it was almost a non-issue. The total size isn't that large to begin with, so it didn't block other requests either. However, if hosted under HTTP/1.1 or an iframe, requests aren't multiplexed, so the overhead will accumulate and performance might degrade.
Another concern is that since Qwik embeds a large amount of metadata in the SSR-ed HTML, even if the JS is minimal, the size of the HTML output could be an issue. As you can see from benchmarking, the cost of parsing HTML is surprisingly high.
Also, and this is a matter of how the user uses it, if you are calling heavy libraries inside the chunks loaded via hydration, the benefit of using Qwik diminishes. There might be some merit in how it isolates issues.
...After considering various factors, I concluded that Qwik(-City) could be used if there are performance requirements and you want to adopt the islands architecture. However, I think it's better to start by using it thinly and delegating most parts to React.
I will talk about that from here.
(About islands architecture: https://jasonformat.com/islands-architecture/)
QwikCity as a Meta-framework
Now for the main topic. By using qwik-react, you can handle React components on Qwik.
// This pragma is required so that React JSX is used instead of Qwik JSX
/** @jsxImportSource react */
import { qwikify$ } from '@builder.io/qwik-react';
// An existing React component
function Greetings() {
return <div>Hello from React</div>;
}
// Qwik component wrapping the React component
export const QGreetings = qwikify$(Greetings);
Example of rendering/hydrating a React component from the Qwik side
import { component$ } from '@builder.io/qwik';
import { QCounter } from './react';
export default component$(() => {
return (
<main>
<QCounter client:load />
</main>
);
});
At this time, you can not only render it as a React component but also control the timing of hydration with Qwik while performing SSR.
What is the benefit of this? In micro-frontends, different UI frameworks are often mixed for each endpoint, making it difficult to use a specific framework for the common parts that serve as the critical path. For example, the micro-frontend library https://single-spa.js.org/ has only minimal template logic and does not target SSR in the first place.
However, with Qwik, while maintaining the lightness of the core (qwikloader: 1kb), you can further suppress the loading/evaluation of JS to a minimum by controlling hydration for other libraries. Moreover, because Qwik itself has expressive power, you can perform processing equivalent to a full-featured SPA if you feel like it, and since qwik-react hydration just calls the real ReactDOM, you can use the full features of React once hydrated.
In other words, you can let Qwik handle only the performance-critical path and routing, making it look like it was loaded via SSR, while letting Qwik perform selective hydration to gradually enable full-featured React. (Actually, there is an option not to SSR using client:only).
And if you use QwikCity as a foundation, you can use File-based routing and server actions, and further write dynamic cache logic using edge-cache like Vercel Edge or Cloudflare Workers. You can also do SSG if you want.
To be honest, Astro can also do selective hydration, but since Astro is basically MPA, you have to load JS normally if you can't write it with built-in triggers. In contrast, Qwik (with enough effort) has the same expressive power as a full-featured Next.js. This is significant.
Example of Delegating Routing from QwikCity to React
When using a router library, a problem arises because page transitions must be delegated to the QwikCity side.
If you use Qwik to its full capacity, it's lightweight enough that MPA transitions would likely be fine, but I went ahead and created a custom Link element for SPA transitions.
/** @jsxImportSource react */
import { createContext, useCallback, useContext, useState } from "react";
const QwikContext = createContext<{
navigate: (href: string) => void;
}>(null as any);
export function AppRoot(props: {
onNavigate: (href: string) => void;
}) {
const navigate = useCallback((href: string) => {
props.onNavigate(href);
}, []);
return (
<QwikContext.Provider value={{ navigate }}>
<div>
hello react
</div>
<Link href="/">Top</Link>
</QwikContext.Provider>
);
}
export function Link(props: {
href: string,
children?: React.ReactNode;
}) {
const { navigate } = useContext(QwikContext);
const onClick = useCallback((ev: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
ev.preventDefault();
navigate(props.href);
}, [navigate, props.href]);
return <a href={props.href} onClick={onClick}>
{props.children}
</a>
}
Pass onNavigate$ from the Qwik side.
import { component$, $ } from "@builder.io/qwik";
import { useNavigate } from "@builder.io/qwik-city";
import { qwikify$ } from "@builder.io/qwik-react";
import { AppRoot } from "./react";
const QAppRoot = qwikfy(AppRoot, {
eagerness: "hover"
});
export default component$(() => {
const navigate = useNavigate();
const onNavigate = $((href: string) => {
console.log("react:navigate", href);
navigate(href);
})
return (
<>
<QAppRoot onNavigate$={onNavigate}/>
</>
);
});
(When passing Qwik props to the React side, the $ QRL is stripped and the actual value is passed.)
From there, it's just a matter of replacing existing Link elements.
Wanting Qwik to Manage More Than Just React
That said, some of you might be thinking that qwik-react is only for Qwik + React. Astro's strength lies in its support for multiple UI libraries, something Qwik currently lacks.
So, I tried creating qwikify for Svelte.
This works.
import App from "./components/App.svelte";
import { qwikifySvelte$ } from "@mizchi/qwik-svelte";
import { component$ } from "@builder.io/qwik";
const QApp = qwikifySvelte$<{name: string}>(App, {
eagerness: 'load',
});
export default component$() => {
return <QApp name="svelte"/>;
};
<!-- src/components/App.svelte -->
<script lang="ts">
export let name: string;
let count = 0;
</script>
<div class="app">
<h1>Hello {name}!</h1>
<button on:click={() => count++}>{count}</button>
</div>
<style>
h1 {
color: blue;
}
</style>
Since I figured out the implementation, I also created qwik-vue.
<!-- src/components/App.vue -->
<script setup>
import { ref, defineProps } from 'vue';
const props = defineProps(["counter"]);
const count = ref(0);
</script>
<template>
<div>{{props.counter}}</div>
<button @click="count++">You clicked me {{ count }} times.</button>
</template>
Similarly, wrap it with qwikifyVue$ to use it.
import { component$ } from "@builder.io/qwik";
import App from "./components/App.vue";
import { qwikifyVue$ } from "@mizchi/qwik-vue";
const QApp = qwikifyVue$<{counter: number}>(App, {
eagerness: 'load',
});
export default component$(() => {
return <QApp counter={0} />;
});
If I were determined, I could probably make versions for Solid or Preact, but since their use cases overlap with Qwik itself, I've put them aside for now.
In addition, based on the opposite idea, I was experimenting with embedding Qwik's static builds into other static pages.
Even though Qwik is an SSR-first framework, there are performance benefits to embedding pre-rendered HTML as a static asset, and this approach might even be preferred due to lower operational costs...
Side Note: Recent SSR/RSC are "Resume" Technologies
Many people misunderstand the nuances of the terminology, but server-side rendering is not simply a regression back to the server-side of the past.
For the frontend, SSR and the hydration process that injects JS logic into it are a set. Therefore, templates that work across both client and server are calculated in multiple stages. To achieve this idempotency, a declarative UI became necessary. As long as idempotency is guaranteed, it doesn't necessarily have to be JS, but since event handler logic must be written, implementation in languages other than JS has become difficult.
While SSR may have originally been born for SEO purposes, modern SSR has become a technology to "resume" (Resume) results calculated halfway on the server on the client side. RSC (React Server Components) basically follows the same idea, where components expanded only on the server are folded into parts of the tree, or conversely, treated as static root elements.
Qwik makes "resumable" one of its core concepts.
Conclusion
I feel that a micro-frontend foundation could be realized by treating Qwik City as a meta-framework. Furthermore, by using Qwik, we can achieve not just simple SSR but also selective hydration, allowing us to reap performance benefits. However, if islands are split too finely, runtimes like react-dom, vue, and svelte/internal will overlap, which could potentially degrade performance.
For adapters other than React, we just have to put in the effort to build them. I was able to write them easily by referring to the implementation of qwik-react, but I postponed the Slot API as it was quite difficult. Actually, as a step prior to Qwik, I was implementing my own islands architecture, but midway through researching Astro and Qwik, I thought "Isn't Qwik good enough?" and simply pivoted the SSR/Hydration I had built up to that point for Qwik.
The biggest concern with this idea is whether Qwik will become popular enough not to become technical debt; regarding this, I have no choice but to do my best writing promotional articles. As for whether I actually want to promote it, I'd like to decide after a bit more research. Also, it probably depends on the motivation of the company builder.io...
Discussion