Wednesday, January 4, 2023
HomeWeb DevelopmentConstructing an app with Qwik

Constructing an app with Qwik


Editor’s notice: This text was peer reviewed by a member of the Qwik group for accuracy.

Qwik is a frontend framework for creating internet functions that gives lightning quick web page load instances, whatever the measurement and complexity of your web site.

On this article, we’ll discover ways to get began with Qwik and discover the constructing blocks of a Qwik utility by making a easy instance app. We’ll additionally evaluation the idea of hydration, study why it slows down our apps, and see how Qwik avoids hydration, boosting our utility’s efficiency. Let’s get began!

Rendering in JavaScript frameworks

Earlier than we will get began with Qwik, we first want to grasp the completely different rendering choices which might be accessible in JavaScript frameworks.

Shopper-side rendering

Early JavaScript frameworks like AngularJS used client-side rendering. In client-side rendering, all logic, information fetching, routing, and templating occurs on the consumer aspect. Nevertheless, a big draw back of client-side rendering is that as an utility grows, the time to render the preliminary web page will increase.

The idea of lazy loading was launched to hurry up the primary render. With lazy loading, as an alternative of sending your entire utility to the browser at one time, you may divide your utility into a number of smaller elements referred to as chunks. When the appliance hundreds for the primary time, you’ll solely ship and execute the required code on the consumer aspect, rushing up the primary render.

Server-side rendering

In server-side rendering, your utility’s first render is already accomplished on the server aspect and despatched to the browser as HTML, rushing up the time of the preliminary render considerably.

Most internet apps usually are not a static webpage. Subsequently, client-side frameworks should recreate the web page after server-side rendering by attaching occasion listeners, making a DOM tree, and restoring the appliance state to make it interactive. This course of is referred to as hydration. The draw back of hydration is that though the web page is rendered on the consumer’s display screen, it won’t be interactive till hydration downloads and re-executes the code once more.

As a framework with out hydration, that is precisely the issue that Qwik tries to unravel.

Getting began with Qwik

To get began, you’ll must have Node.js ≥v16.8 put in.

Qwik comes with a CLI instrument that helps you scaffold your utility. First, generate your app utilizing the next command:

npm create [email protected]

The command above will immediate you to call the appliance; let’s select dice-roller. It’ll additionally immediate you to pick out the kind of utility; choose Fundamental App (QwikCity). It will generate a listing referred to as dice-roller inside a Qwik utility.

Let’s navigate to the dice-roller listing utilizing the next command:

cd dice-roller

Now, let’s begin the dev server to run our app:

npm begin

To see how the app appears, open http://localhost:5174.

Qwik app construction

In the event you open the undertaking listing in your code editor, you’ll see the next folder construction:

├── README.md
├── node_modules
├── package-lock.json
├── package deal.json
├── public
├── src
├── tsconfig.json
└── vite.config.ts

There are a number of key issues to grasp right here:

  • TypeScript: By default, Qwik functions help TypeScript, as indicated by tsconfig.json
  • Vite: Throughout improvement, Qwik makes use of Vite
  • src: By default, the src listing is used for supply code
  • public: The public listing is used for static property

Instance Qwik app: Cube roll app

For this app, we’re utilizing QwikCity, which is a meta framework for Qwik, identical to Subsequent.js is to React. We’ll use QwikCity to offer a directory-based router and entry to the tree of parts. In the event you open src/parts/routes/index.tsx, you’ll see the default route / exporting a Qwik element with some content material.

Exchange the content material of file with the next code, which simulates a six face cube roll:

import { element$, useStore } from "@builder.io/qwik";

export const randomValue = () => Math.ground(Math.random() * 6) + 1;

export default element$(() => {
  const cube = useStore({
    worth: 1,
  });

  return (
    <div>
      <h2>Cube curler</h2>
      <h3>Cube worth: {cube.worth}</h3>
      <div>
        <button onClick$={() => (cube.worth = randomValue())}>Roll</button>
      </div>
    </div>
  );
});

In the event you save the file and open the browser at https://localhost:5174, you’ll see the next app:

Qwik Dice Roller Example App

Ignore the header and footer, they’re a part of default utility. The code that you simply modified is printed with a pink field. Let’s perceive it intimately.

Because the title suggests, the element$ methodology creates a element. The element$ methodology comes from the builder.io/qwik package deal. Discover the $ image; it has a particular that means that we’ll focus on quickly.

Once more, like React, a element can have props, which you should use to move inputs to the element. A Qwik element makes use of jsx. The JSX template is returned from a element that creates the UI.

useStore is a Qwik Hook that means that you can create a state like React’s useState. Each time an app reads or writes these values, Qwik is conscious of it, re-rendering the UI accordingly.

The onClick$ is an attribute that means that you can bind a click on occasion handler on a component. You’ll be able to create occasion handlers for numerous forms of occasions. Lastly, the randomValue methodology generates a random worth between one and 6.

In abstract, in Qwik, you will have parts, JSX, Hooks, and occasions, like React. Nevertheless, there’s a vital distinction in comparison with React, and that’s how Qwik avoids hydration.

The greenback signal $

Qwik comes with an optimizer, which is accountable for extracting code for lazy loading. This optimizer goes via the app code, and when it encounters the greenback $ signal, it creates what known as a logo. These symbols can then be simply lazy loaded.

Within the element instance above, you will have two locations the place $ exists; first at element$, and second in onClick$.

Qwik will generate symbols for the next:

  • For element
  • For onClick occasion handler

The $ signal can also be a sign to the developer that the code has a particular that means.

HTML

After the code is rendered on the server-side, Qwik will generate HTML and ship it to the browser. The markup will seem like the next:

<html>
  <physique q:base="/construct/">
    <!--qv q:id=0 q:key=Ncbm:0t_0-->
    <div>
      <h2>Cube curler</h2>
      <h3>
        Cube worth:
        <!--t=1-->1<!---->
      </h3>
      <div>
        <button
          on:click on="app_component_div_div_button_onclick_yuuzzqjuatw.js#app_component_div_div_button_onClick_YuUzZQjuATw[0]"
          q:id="2"
        >
          Roll
        </button>
      </div>
    </div>
    <!--/qv-->
    <script>
      /*Qwikloader script*/
    </script>
    <script sort="qwik/json">
      {...json...}
    </script>
  </physique>
</html>

You may discover that there aren’t any JavaScript occasion handlers on the HTML parts. That’s one motive why Qwik is quick with regards to the first-render. No JavaScript means no hydration. Now, how does interactivity work?

Qwikloader

Wanting on the <button> aspect, you’ll discover that it has a bizarre attribute, on:click on. The browser will ignore this attribute by itself. Nevertheless, Qwik makes use of this attribute utilizing Qwikloader, a small JavaScript code delivered as an inlined <script> tag.

This attribute has a strange-looking worth:

app_component_div_div_button_onclick_yuuzzqjuatw.js#app_component_div_div_button_onClick_YuUzZQjuATw[0]

This unusual worth known as QRL, or a Qwik URL. This URL gives the next info:

  • The JavaScript chunk to lazy-load
  • The title of the image to get from the chunk

Utilizing this URL, Qwikloader will know what code to fetch and execute from the chunk generated by the optimizer. However what in regards to the state? How does the newly fetched code know the present state of the appliance?

State

Qwik additionally saves the state of the appliance in serialized kind utilizing a <script> tag within the HTML. It appears one thing like the next:

<script sort="qwik/json">{
  "refs": {
    "8": "0!"
  },
  "ctx": {},
  "objs": [
    {
      "value": "1"
    },
    1
  ],
  "subs": [
    [
      "2 #6 0 #7 data"
    ]
  ]
}</script>

Qwik makes use of the serialized state for the next causes:

  • To restart the execution on the client-side after it’s paused on the server
  • To create subscriptions on the client-side to re-render solely the element that modified

This skill to renew the appliance utilizing lazy-loading and entry serialized state with out downloading all the appliance code is named resumability.

Deploying

When you end your utility, you may deploy it to any surroundings the place Node.js is on the market. Qwik gives built-in to integrations that will let you rapidly deploy to internet hosting companies like Netlify, Vercel, and extra.

You’ll be able to add any integration by operating the next command:

npm run qwik add

On the time of writing, Qwik helps the next integrations:

For example, if you wish to deploy on Netlify, you may run the next command:

npm run qwik add netlify-edge

Then, you may run the next instructions to deploy your utility to Netlify:

npm run construct
npm run deploy

Conclusion

On this article, we discovered how one can get began with Qwik. We lined some rendering strategies and explored a number of of Qwik’s key APIs together with parts, hooks, and occasions.

We discovered how Qwik makes functions resumable by utilizing Optimizer, Qwikloader, and QRL. That is simply the tip of the iceberg. To study extra, go to https://qwik.builder.io to study extra about QwikCity, Builder, Partytown and so forth.

Are you including new JS libraries to enhance efficiency or construct new options? What in the event that they’re doing the alternative?

There’s little doubt that frontends are getting extra complicated. As you add new JavaScript libraries and different dependencies to your app, you’ll want extra visibility to make sure your customers don’t run into unknown points.

LogRocket is a frontend utility monitoring answer that allows you to replay JavaScript errors as in the event that they occurred in your individual browser so you may react to bugs extra successfully.


https://logrocket.com/signup/

LogRocket works completely with any app, no matter framework, and has plugins to log extra context from Redux, Vuex, and @ngrx/retailer. As an alternative of guessing why issues occur, you may mixture and report on what state your utility was in when a difficulty occurred. LogRocket additionally displays your app’s efficiency, reporting metrics like consumer CPU load, consumer reminiscence utilization, and extra.

Construct confidently — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments