Basics of Qwik Framework(simplified)
Hello there, my name is Denis. A frontend Expert. Today, we are going to look at Qwik basics just to understand how it works.
Key takeaways
- It is a Frontend Framework
- Extremely fast, apps starts up almost instantly.
- Downloads and Executes code that is necessary.
- Bring in new approach of developing apps that are resumable.
- Offers the fastest page load times for complex sites e.g ecommerce sites.
- it uses precision-lazy loading.
Intallation
To install just run npm create qwik@latest
. Note that qwik will run only with nodev16+
. Make sure you install the latest version of nodejs to enjoy the amazing experience of qwik framework.
Hello World in qwik
How does qwik code look like? Well, if you ask me, qwik is more or less like writing React as it uses Jsx but it is not React.
Lets take a look at an example:
import {component$ } from '@builder.io/qwik'
export const HelloWorld = component$(()=> {
return <div>Hello world</div>
})
Points to note
- Import the
component$
function. The$
at the end tells qwik that the function is lazy-loadable and resumable. - Declare and export a component which is the result of what is returned by our
component$
function - The
component$
takes an arrow function and returns jsx code.
Clear? Don't worry, we shall take a look at couple of more examples
Handling click events
import {component$ } from '@builder.io/qwik'
export const Button = component$(()=> {
return (
<button onClick$={()=> {alert('On click!')}>Click me</button>
)
})
To listen an event you add an event property name with $
at the end. e.g onClick$
, onInput$
etc.
Again, whenever you see $
, know that it means the function will be lazy loaded.
Declaring state
State management in qwik is done using useStore()
function.
The function does the following:
- It stores state
- Presents store as proxy that can detect changes e.g read or write.
- Serialize store data into json on application pause.
- Create subscription to store.
- Observe what properties are used by what components.
Exampe:
import { component$, useStore} from '@builder/qwik';
const store= useStore({
value:0
})
export const StateExample = component$(()=> {
return <div>{store.value}</div>
});
Change the value of Store
This example will show you how you can change the state value when user click on button
import {component$, useStore} from '@builder/qwik';
export const useStore({
value:0
});
export default ClickComponent(() => {
return (<div>
<h4>The value is:{store.value}</h4>
<button onClick$={()=> store.value++}></button>
</div>)
})