Take a Qwik Break from React with Astro
Before we get going, a disclaimer: I love React but sometimes, I really don’t need it.
Many of my recent projects have been built using Astro (which by default ships zero JavaScript to the client — superb for fast, lightweight and performant content websites). But on occasion, I have needed a little bit of client-side JavaScript to enable interactivity. At this point, I’ve found myself struggling to decide between regular Vanilla JavaScript or React.
On one hand, Vanilla JavaScript is generally more lightweight than React, but it can become difficult to maintain. React somewhat solves this problem, but for minimal client-side JavaScript requirements, it is a bit of a beast.
For these reasons (and a number of others) I started to investigate alternatives to React. And lo and behold, I discovered Qwik.
What Is Qwik?
The official product marketing message is as follows: “Qwik is a new kind of web framework that can deliver instant loading web applications at any size or complexity.”
For me, however, I like to think of Qwik like this: Write code like React, Browser tastes of Vanilla.
Qwik is fundamentally different from React and has been designed from the ground up to facilitate the growing demand for frameworks to work on both the client and the server.
Qwik is lighter than React and less verbose than Vanilla, and doesn’t need any additional 'use client'
, or client:load
directives. It’s smart enough to execute (where necessary) on the server, and resume on the client. The Qwik team has done a much better job of explaining it than I ever could so head over to the docs to find out more: Think Qwik.
Qwik Astro Integration
As I mentioned, my current exploration into Qwik has mainly been focused around my work with Astro. The excellent @quikdev/astro integration from Jack Shelton has made getting started with Qwik an absolute dream. Here’s a snippet from the docs. As you can see, getting started is as simple as installing the integration and adding it to your Astro config.
1 2 3 4 5 6 7 8 |
// astro.config.mjs import { defineConfig } from 'astro/config'; import qwikdev from '@qwikdev/astro'; export default defineConfig({ integrations: [qwikdev()], }); |
Reluctance to Switch
I can understand the reluctance to switch. Many of my “React friends” have exhibited an unwillingness to make the switch by claiming they know React and don’t want to invest the time in learning something new. That’s a fair point, but how different are the two technologies really?
In the following code snippets, I’ll be covering some common React use cases and showing you how you’d accomplish the same using Qwik. Hopefully, you’ll agree that it’s not an overly steep learning curve.
With all that out of the way, we can now get going!
Simple Component
Here’s a simple React component.
React Simple Component
1 2 3 4 5 6 7 8 9 10 11 |
import React from 'react'; const SimpleReactComponent = () => { return ( <div> <p>Hello, I'm a simple React component</p> </div> ); }; export default SimpleReactComponent; |
And here’s the Qwik version.
Qwik Simple Component
1 2 3 4 5 6 7 8 9 10 11 |
import { component$ } from '@builder.io/qwik'; const SimpleQwikComponent = component$(() => { return ( <div> <p>Hello, I'm a simple Qwik component</p> </div> ); }); export default SimpleQwikComponent; |
The main difference is the use of component$
. A full explanation can be found in the Qwik docs here: component$.
State vs. Signal
In the following example, a button click sets the value of isVisible
to either true
orfalse
.
This boolean value is used to determine if the <span />
containing the Rocket emoji is returned by Jsx. it’s also used to display either the word “Show” or “Hide” in the button.
You can see src
code and a preview of this Qwik component on the links below.
- Preview: https://qwik-break-from-react.netlify.app/use-signal-qwik-page/
- Repo: https://github.com/PaulieScanlon/qwik-break-from-react/blob/main/src/components/qwik/use-signal-qwik-component.jsx
useState React Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { useState } from 'react'; const UseStateBooleanReactComponent = () => { const [isVisible, setIsVisible] = useState(true); const handleVisibility = () => { setIsVisible(!isVisible); }; return ( <div> <p> <span> {isVisible ? ( <span role='img' aria-label='Rocket'> 🚀 </span> ) : null} </span> Hello, I'm a useState boolean React component </p> <button onClick={handleVisibility}>{`${isVisible.value ? 'Hide' : 'Show'} Rocket`}</button> </div> ); }; export default UseStateBooleanReactComponent; |
useSignal Qwik Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { component$, useSignal, $ } from '@builder.io/qwik'; const UseSignalQwikComponent = component$(() => { const isVisible = useSignal(true); const handleVisibility = $(() => { isVisible.value = !isVisible.value; }); return ( <div> <p> <span> {isVisible.value ? ( <span role='img' aria-label='Rocket'> 🚀 </span> ) : null} </span> Hello, I'm a useSignal Qwik component </p> <button onClick$={handleVisibility}>{`${isVisible.value ? 'Hide' : 'Show'} Rocket`}</button> </div> ); }); export default UseSignalQwikComponent; |
The main differences here are with how the handler is defined and how the state, or signal, is declared.
Function declarations are wrapped with $()
, which transforms the function into a QRL. You can read more about function handlers in the docs here: Reusing event handlers.
Inside the function is where things get a little more different. With Qwik you update the signal value directly. E.g isVisible.value = true
. A signal will only contain the value, and not the setter pair, like React’s useState
.
And lastly, watch out for the trailing $ on the onClick attribute. E.g onClick$
.
State vs. Store
In the following example, the + button adds a Rocket to an array, the – button removes the last item added. Each time the array is modified the page is updated to reflect the change.
You can see src
code and a preview of this Qwik component on the links below.
- Preview: https://qwik-break-from-react.netlify.app/use-store-qwik-page/
- Repo: https://github.com/PaulieScanlon/qwik-break-from-react/blob/main/src/components/qwik/use-store-qwik-component.jsx
useState React Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { useState } from 'react'; const UseStateBooleanReactComponent = () => { const [rockets, setRockets] = useState(['🚀']); const handleAdd = () => { setRockets((prevState) => [...prevState, '🚀']); }; const handleRemove = () => { setRockets((prevState) => [...prevState.slice(0, -1)]); }; return ( <div> <div className='h-8'> {rockets.map((data, index) => { return ( <span key={index} role='img' aria-label='Rocket'> {data} </span> ); })} </div> <p>Hello, I'm a useState array React component</p> <div className='flex gap-4'> <button onClick={handleAdd}>+</button> <button onClick={handleRemove}>-</button> </div> </div> ); }; export default UseStateBooleanReactComponent; |
useStore Qwik Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { component$, useStore, $ } from '@builder.io/qwik'; const UseStoreQwikComponent = component$(() => { const rockets = useStore(['🚀']); const handleAdd = $(() => { rockets.push('🚀'); }); const handleRemove = $(() => { rockets.pop(); }); return ( <div> <div className='h-8'> {rockets.map((data) => { return ( <span role='img' aria-label='Rocket'> {data} </span> ); })} </div> <p>Hello, I'm a useStore Qwik component</p> <div className='flex gap-4'> <button onClick$={handleAdd}>+</button> <button onClick$={handleRemove}>-</button> </div> </div> ); }); export default UseStoreQwikComponent; |
Similar to the useSignal
example, the function declarations are wrapped with $()
but in my opinion, the way to update the array is more straightforward. A simple/standard JavaScript .push
or .pop
can be used, rather than the React method of having to spread the previous state before modifying it.
Client-Side Data Fetching
In the context of Astro it might feel odd to even have a client-side data request, but every now and then you probably will need a bit of client-side data fetching — and here’s how you can do that.
You can see src
code and a preview of this Qwik component on the links below.
- Preview: https://qwik-break-from-react.netlify.app/client-fetch-qwik-page/
- Repo: https://github.com/PaulieScanlon/qwik-break-from-react/blob/main/src/components/qwik/client-fetch-qwik-component.jsx
useEffect React Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { useState, useEffect } from 'react'; const ClientFetchReactComponent = () => { const [data, setData] = useState(null); useEffect(() => { const getData = async () => { const response = await fetch('https://api.github.com/repos/BuilderIO/qwik/pulls/1', { method: 'GET', }); if (!response.ok) { throw new Error(); } const json = await response.json(); setData(json); try { } catch (error) { console.error(error); } }; getData(); }, []); return ( <div> <p>Hello, I'm a simple Client fetch React component</p> {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : Loading...} </div> ); }; export default ClientFetchReactComponent; |
useVisibleTask Qwik Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import { component$, useVisibleTask$, useSignal } from '@builder.io/qwik'; const ClientFetchQwikComponent = component$(() => { const data = useSignal(null); useVisibleTask$(async () => { try { const response = await fetch('https://api.github.com/repos/BuilderIO/qwik/pulls/1', { method: 'GET', }); if (!response.ok) { throw new Error(); } const json = await response.json(); data.value = json; } catch (error) { console.error(error); } }); return ( <div> <p>Hello, I'm a simple Client fetch Qwik component</p> {data.value ? <pre>{JSON.stringify(data.value, null, 2)}</pre> : Loading...} </div> ); }); export default ClientFetchQwikComponent; |
As you probably know, React’s useEffect
has to return a function, not a promise. In order to fetch data asynchronously on page load, a useEffect
with an empty dependency array needs to contain a function that can use async/await
.
Qwik, however, has useVisibleTask — which can return a promise. useVisibleTask
is only executed in the browser, but if you do want to use a similar approach for server-side data fetching, Qwik also has useTask.
Wrapping Up
These are just a few examples of the differences/similarities between React and Qwik, and I for one am really coming around to the Qwik way of thinking. For quite a long time now I’ve had what some describe as “React brain,” but taking a quick break from React impelled me to look around and see what the rest of the JavaScript mega-legends have been up to (Qwik was created by Angular creator Miško Hevery).
It might be scary even considering migrating away from React, but when thinking about what React was (a client-side state management library) and what it’s now being re-engineered to be… [insert your understanding here], now is probably a good time to investigate your alternatives.
No one knows what the future holds, but at the very least, Qwik was designed in the here and now to work in the here and now, and I’ve been really enjoying the experience so far. Go team Qwik!