Qwik is a cutting-edge front-end framework designed for building efficient, resumable web applications. It stands out by enabling lightning-fast application startup times on the client side. Qwik achieves speed by downloading and executing only the necessary code for user actions.
Unlike traditional server-side rendered (SSR) frameworks, Qwik operates without the need for a process known as "hydration." In SSR applications, the client-side boot-up involves restoring event listeners, the component tree, and the application state. This restoration process, called hydration, can be resource-intensive as it necessitates the download of all component code associated with the current page.
Qwik's distinct advantage lies in its speed and efficiency. By circumventing the hydration process, it eliminates the need for downloading excessive code, resulting in a responsive and performant client-side experience.
Let’s explore the process of building a quiz application with Qwik.
Setting up the development environment
Before you begin, you should:
- Download and install NodeJS
- Set up your favorite IDE (vscode recommended)
- Create a Netlify account for deployment (optional)
Create your Qwik application
Initialize a new Qwik application using the Qwik CLI. The CLI generates a basic starter template. Open the terminal or command prompt and run the Qwik CLI by executing one of the following commands based on your preferred package manager, whether it’s NPM, Yarn, or PNPM.
Start the development server:
Designing the Quiz application
In building the quiz application, we would dive into the most important Qwik concepts such as directory-based routing, and state management.
Create quiz route
Routing in Qwik relies on QwikCity, Qwik’s meta-framework. To learn more about QwikCity, an in-depth dive is available on Bejamas discovery. QwikCity uses directory-based routing, similar to frameworks like Next.js, SvelteKit, SolidStart, or Remix. Files and directories within the
src/routes directory define the routing structure of the application. To get started:
Inside your Qwik project's
src/routes directory, create a new folder named
quiz. Inside the
quiz directory, create an
index.tsx file, content is defined using the
export default component$(...) syntax.
Components serve as the fundamental building blocks of a Qwik application. They are defined using the
component$() function and, at the very least, are expected to return a JSX element.
Navigate to http://localhost:5173/quiz/ to see the new page.
Create body of quiz application
In the defined component function, define the JSX markup.
This code block renders the quiz questions, quiz results and its options. It conditionally renders the quiz results when `store.showResult` is `true`. Displays the overall score, the total number of questions, the total score, the number of correct answers, the number of wrong answers, and a button to restart the quiz.
Create a new file
quiz.module.css inside the
quiz directory and import into the
Now you can paste the styles from the GitHub repository to this file.
Implementing quiz functionality
Create dummy data
The data represents a set of quiz questions and answers, structured in TypeScript interfaces. The data is essential for populating the quiz content and testing the functionality of the application.
src directory, create a
data.ts file and paste the code into the
Managing application state
In Qwik, there are two types of state, static or reactive. The static state encompasses any data that is serializable, encompassing a wide range of types, including strings, numbers, objects, and arrays. The reactive state, on the other hand, is created using
In this application, the
useStore() function is employed, and it differs from
useSignal() in its initialization process. Specifically,
useSignal() accepts an initial value, which can be a simple value like
useStore() expects an object as its initial value. To get started:
quiz object from the
data file. Import the
useStore() function from the
QuizStore interface, this defines the structure of the state that the
useStore function will manage.
Inside the component function,
useStore is used to initialize the application’s state using the
QuizStore interface. The
useStore function accepts an initial state object as its argument, which populates the initial values of the state properties.
The store object is initialized with properties defined in the
QuizStore interface, providing initial values for the quiz-related variables. These variables include the active question, selected answer, the selected answer's index, whether to show quiz results and an object to store the quiz result details such as score, correct answers, and wrong answers.
Handling user responses
To make the Quiz application useful, it’s important to be able to handle user responses and check if the user has entered the correct answers.
Accessing quiz data:
questions array is extracted from a
quiz object. The array contains a list of quiz questions, each with its question statement, answer options, and the correct answer.
Extracting current question data:
store.activeQuestion represents the index of the currently active question.
Handling user selection:
This function is called when a user selects an answer option. It takes two parameters:
idx (the index of the selected answer in the
answers array). The selected
answer is then compared with the
correctAnswer for the current question.
In the above code implementation, you may have noticed the
$ sign in front of the function declaration. Qwik divides the application into smaller units known as
symbols. These symbols are finer-grained than components, allowing a component to be decomposed into multiple symbols. The process of splitting is managed by the Qwik optimizer.
The presence of the
$ suffix serves as a signal to both the optimizer and developers, indicating when the division takes place. When using Qwik, developers need to be aware that certain specific rules come into play whenever they encounter the
Navigating to the next question
This section demonstrates how to update the quiz state and move to the next question after a user selects an answer.
nextQuestion function is responsible for advancing to the next quiz question after the user has interacted with the current one.
Updating the quiz score and answer status:
If the user's selected answer
store.selectedAnswer is correct, increment the quiz score by 5 points and update the count of correct answers in the result object. If the selected answer is incorrect, increment the count of wrong answers in the result object.
Navigating to the next question:
This checks if the current question is not the last question in the quiz by comparing
questions.length - 1. If it's not the last question, we increment
store.activeQuestion to move to the next question.
Resetting state for the next question:
This resets the
store.selectedAnswer to null to clear the user's selected answer for the next question. Then, reset
store.checked to false, indicating that the user has not yet interacted with the next question.
Adding a countdown timer
It’s important to incorporate a countdown timer into the quiz application. A timer is a valuable addition to the application as it provides users with a time limit for answering each question.
Update application state:
Add the following code In the
QuizStore interface and
QuizStore state instance:
intervalId keeps track of the active timer, the timer variable tracks the number of available seconds.
Create startTimer function:
startTimer function starts a countdown timer if there isn’t an already active timer. The timer checks the remaining time and decrements by 1 second. Once time runs out, it proceeds to the next question.
Update nextQuestion function:
There is a need to trigger the
startTimer function and reset the state in store.timer after navigating to the next question.
Ensuring timer resumability:
When creating the timer functionality, it is important to have it run on the browser after rendering. In that case, the
useVisibleTask$() function from Qwik is used. The
useVisibleTask$() function registers a hook that triggers when the component becomes visible within the viewport. The hook executes at least once when the component loads in the web browser. It provides almost the same functionality as useEffect in React.
In the dependency section, import
Inside the component body, define the
This hook triggers the
startTimer function when the component turns visible.
Creating authentication in Qwik
Only authenticated users should be able to access the quiz. Let's see how to create authentication in Qwik and the handling of server logic. The
server$() function is a tool in Qwik that enables the creation of functions that run on the server. This capability is useful for tasks involving database access or server-side operations.
server$() is a way to establish a Remote Procedure Call (RPC) mechanism between the client and server. When you create a function using server$(), it takes on a specific signature:
([AbortSignal, ] ...): Promise<T>. Let’s explore how to integrate functions created with server$() into our application.
Create server authentication function:
quiz directory, create a file called
server.ts and paste the below code.
This code is meant to run exclusively on the server.
index.tsx file in the
quiz directory, import the
serverAuthenticate function from the
Update Application State:
Add the following code In the
QuizStore interface and
QuizStore state instance:
useSignal() into application dependencies:
useSignal() creates a form of state called a reactive signal. It takes an initial value and returns a reactive signal. The reactive signal returned consists of an object with a single property called
Defining username and password state:
In this application,
useSignal is used to create state variables for tracking the value of the username and password entered by the user. Inside the component body, add the following code.
Create login functionality:
When a user attempts to log in, the
login function is triggered. Inside the login function, a server authenticated process is initiated by calling the
serverAuthenticate function. This function communicates with the server to verify the provided credentials.
After creating and testing the login functionality, an issue has arisen.
useVisibleTasks$() triggers when the component mounts, which means our timer starts running before log in. To prevent this, let's update the application.
Switch from using useVisibleTask$ to useTask$
Introduction to useTask$:
useTask$() is similar to
useVisibleTask$() but provides added functionality. Unlike
useVisibleTask$() which runs immediately after the component renders,
useTask$() is reactive. This means that a task is trackable and re-executes when the tracked state changes.
In the dependencies, import
@builder.io/qwik and import
A variable for tracking authenticated users needs to be set up. The
useTask$ tracks this variable and runs the timer when the user is successfully logged in.
useSignal, create a reactive signal for checking user authentication.
Update login function to update
userAuthenticated.value updates to true once the user is authenticated.
Switch from using
Comment out the
useVisbleTask$ and replace it with the code block below.
With this update, the
startTimer function runs once the user is authenticated.
Voila. If you made it this far, the quiz application is complete and it’s time for you to play with it. Navigate to http://localhost:5173/quiz/ in your browser to see the application.
Deploying the quiz application
Qwik makes it easy to deploy applications with its ready-to-use integrations. Qwik City provides middleware that acts as glue code for connecting to server rendering frameworks. It enables connection to Cloudflare, Netflify, Vercel, and Express. To activate the middleware for connecting with a server rendering framework, run the below command.
This provides a wide array of middleware adapters to choose from based on your preference.
This tutorial makes use of Netlify edge functions, so choose Netlify Edge from the provided options.
With edge functions our application is thus rendered at an edge location near our users. Before proceeding further, install the Netlify CLI.
To install the Netlify CLI on Mac, in your terminal window, run the following command.
To build the application for production, use the build command. This command runs
npm run build.server and
npm run build.client. This builds our site for both ssr and static content.
Run the following command:
To deploy the application for development, run the following command:
This command creates a website draft URL. The draft URL provides the ability to see how the application runs when served before deploying to production. Run the website draft URL to see how it behaves when served. If there are no errors, run the production deployment.
To deploy to production, run the following command:
Thank you for reading this far. You can access the production version of the application at the following URL: https://qwikquizapp.netlify.app/quiz/.
To log in, use the following credentials:
- Username - user
- Password - password.
Also, you can find the code on the Bejamas page on GitHub.
This tutorial has provided valuable insights into Qwik and how it can be used to create high-performance web applications. Thank you for joining this Qwik journey, and I look forward to seeing the amazing applications you'll build with this framework.
Recap of the key features and benefits of using Qwik
- Efficiency and speed: Qwik is great at building efficient and resumable web applications. It excels at delivering fast application startup times on the client side. By downloading and executing only the necessary code for user actions, Qwik excels in delivering fast web applications. It eliminates unnecessary code bloat and ensures a responsive and performant user experience.
- No hydration required: unlike traditional server-side rendered (SSR) frameworks, Qwik operates without hydration. It cuts out a resource-intensive process of restoring event listeners, and rehydrating the component tree. Qwik's approach hence streamlines the client-side boot-up process.
- Component-based architecture: components serve as the building blocks of Qwik applications. Qwik enforces a structured component-based architecture, making it easy to create modular code.
- State management: Qwik provides different types of state management, including static and reactive state. In the tutorial, useStore() is used for managing the application state. It initializes the state with an object, allowing the management and updating the state of the application.
- Server-side logic: with server$(), Qwik allows the creation of server-side logic that is invokable from the client side.
- Production-ready: Qwik includes production-ready features, such as server rendering, static site generation, and routing, making it suitable for building both small and large-scale web applications.
Further exploration of advanced usage of Qwik
Let's explore critical aspects that underpin Qwik's efficiency and power, such as serialization and the Qwik Optimizer. Serialization, in the context of Qwik, plays a pivotal role in enabling resumable web applications.
What is the purpose of serialization?
Serialization, at its core, involves converting data into a format to be stored or transmitted and later reconstructed. This process is often compared to
Overcoming JSON limitations in Qwik
JSON's limitations pose challenges for developers, especially when dealing with complex application states. Qwik addresses some of these limitations head-on by:
- Handling circular references: JSON produces a Directed Acyclic Graph (DAG), which means it cannot handle circular references. This limitation becomes significant when dealing with application states that involve circular references. Qwik ensures that circular references within the graph of objects are saved during serialization and later restored, overcoming this limitation.
- Serializing complex object types: JSON struggles with certain object types, such as DOM references and dates, which it cannot serialize. Qwik's serialization format comes to the rescue by ensuring that these problematic objects can be serialized and restored. This extended support also includes types like URL objects, promises, and even map and set instances.
While Qwik goes a long way in addressing the limitations of JSON serialization, it's essential to note that there are some limitations it cannot solve:
- Serialization of classes: JSON's inability to serialize classes, particularly instances of classes, remains a limitation. Qwik addresses this by supporting some built-in classes like Date, URL, Map, and Set. However, for user-defined classes, serialization remains a challenge.
- Serialization of streams: the complex nature of streams makes them challenging to serialize. In cases where serialization is not feasible, the code should run only on the client, acknowledging this limitation.
Writing Qwik applications with serialization in mind
To harness the full power of Qwik and its resumability capabilities, developers need to adopt a new mindset when writing web applications. It's imperative to consider the resumability of both the framework and the application itself. This means expressing components and entities in a way that can be serialized and resumed without the need for re-bootstrapping.
Developers must shift from a heap-centric approach to a DOM-centric one. This paradigm shift requires a change in behavior and a retooling of web development skills. Frameworks like Qwik play a crucial role in providing guidance and APIs to ease this transition, making it easier for developers to write applications with serialization and resumability in mind.
Additional benefits of resumability
While server-side rendering is the most apparent benefit of resumability, there are other advantages to consider:
- Progressive Web Apps (PWAs): serializing existing PWAs ensures that users don't lose context when they return to the application, enhancing the user experience.
- Improved rendering performance: resumability allows for fine-grained lazy-loading, meaning only changed components need to be re-rendered. This results in improved rendering performance and a more responsive application.
- Reduced memory pressure: especially crucial on mobile devices, resumability can decrease memory pressure by optimizing the usage of system resources.
- Progressive interactivity: even static websites can benefit from resumability by enhancing interactivity as users engage with the site.
Understanding the Qwik Optimizer
The Qwik Optimizer operates as a Vite plugin during bundling. Its primary purpose is to divide applications into small, lazy-loadable chunks. It identifies and moves expressions, typically functions, into new files, leaving behind references to the original locations. The dollar sign ($) informs the optimizer which functions to extract into separate files and which ones to leave untouched. The optimizer relies on the $ suffix to identify functions for transformation.
Rules for using $
The Qwik optimizer uses $ as a signal to extract code, and developers must adhere to specific rules when working with it. These rules ensure that the extracted code remains valid and optimized.
1. Allowed Expressions
The first argument of any function ending with $ must meet specific restrictions:
- It should contain literals without local identifiers.
- Importable identifiers are allowed.
- Closures have slightly relaxed rules, allowing local identifiers to be referenced and captured.
- Captured variables must be declared as a const.
- Captured variables must be serializable.
3. Module-declared variables
- Functions extracted by the Optimizer should refer to top-level symbols, either imported or exported.
Consider a scenario where you want to implement a scroll event handler lazily. The traditional approach requires the manual separation of code into different files and hardcoding chunk names. However, Qwik simplifies this process by using the $() marker function.
By wrapping a function in $(), developers signal the Optimizer to move the function to a new file for lazy loading. It allows for easier code organization and chunking without manual intervention.
The Qwik Optimizer excels at breaking down code into smaller chunks, enhancing the application's maintainability and performance. For instance, when a component is defined with component$(), the Optimizer extracts its methods into separate files, improving code separation and facilitating lazy loading.
Capturing the lexical scope
In complex scenarios where extracted function closures capture variables, Qwik handles the situation gracefully. It stores these variables in the QRL (Qwik Resource Locator) and generates code that restores the lexical scope when needed. This powerful feature enables the extraction of more functions into lazy-loaded resources, contributing to more efficient code splitting.
Understanding serialization and the
$ in Qwik is essential for harnessing the full potential of the framework. By addressing JSON's limitations and emphasizing resumability, Qwik empowers developers to build high-performance web applications that are not only efficient but also capable of delivering a superior user experience.
The dollar sign ($) in Qwik is not just a symbol. It's a gateway to optimizing your web applications. By understanding the rules and techniques associated with the dollar sign, developers can leverage Qwik's capabilities to create highly modular, efficient, and maintainable web applications.