Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
With Vue 3 gaining traction and becoming the new default, many things are changing, and the ecosystem is still shaping. Until recently, the choice for state management was clearly Vuex. But with the new composition API architecture, reactivity mechanism, and some new players in the game, the choice now might be different.
Let’s explore different ways of managing the state depending on your application size and try to predict what the future of State Management in Vue.js will look like.
In options API, you can declare reactive data for a component using the data() option. Internally the object returned is wrapped with the reactive helper. This helper is also available as a public API.
If you have a piece of state that should be shared by multiple instances, you can use reactive() to create a reactive object and then import it from multiple components:
With this approach, data are centralized and can be reused across components. This can be a simple option with a minimal footprint for a small application.
A similar concept that composition API brought to the table is using a composable. This pattern, which is very popular in the React world, combined with the powerful reactivity mechanism of Vue can produce some elegant and reusable composables like the following.
Vuex is not going away. It supports Vue 3 with the same API and minimal breaking changes. The only change is that installation must happen on a Vue instance instead of the Vue prototype directly.
Vuex 4 will still be maintained. However, it’s unlikely that new functionalities will be added to it. It’s a good option if you already have a project using Vuex 3 and want to defer the migration to something else for later.
Pinia is a new store/state management system for Vue. This is a great tool for when wanting to share data between components in your application. One of the reasons for using a tool like Pinia (or Vuex for that matter) is that throwing events around and listening for these events in your application can easily become quite messy and unstructured. State management systems like Pinia (Vuex, Redux, etc.) can help solve this.
Pinia is now also the recommended choice by Vue and is now an official part of the whole Vue ecosystem, maintained and developed by core members of the Vue team. Last but not least, Pinia is super lightweight, only 1kb in size which is freaking awesome.
Pinia supports an alternative syntax to define stores. It uses a function that defines reactive properties and methods and returns them very similar to the Vue Composition API’s setup function.
In Setup Stores:
Setup stores bring a lot more flexibility than Options Stores as you can create watchers within a store and freely use any composable.
The state is a function that holds all the reactive data of this store and the getters are functions with access to the store as the first parameter. Both state and getters are identical to Vuex.
This statement doesn’t apply to actions. The context parameter has gone, and actions have access to the state and getters directly through their context(this). As you might have noticed, actions directly manipulate the state, which was strictly forbidden in Vuex.
Lastly, mutations are completely removed since state manipulation is now happening in actions.
All the magic is happening inside the setup function. The imported useFellowship hook is executed and returned. This will make it available to the component, including both methods and the template. Access to the state getters and actions are done directly using this object.
Of course, this component should be broken into smaller reusable ones but left like this for demo purposes.
If a different component needs to access the same state, it can be done in a similar manner.
Pinia docs are optimistic that code can be reused between the libraries, but the truth is that the architecture is very different, and refactoring will definitely be required. First of all, while in Vuex, we had one store with multiple modules, Pinia is built around the concept of multiple stores. The easiest way to transition that concept to be used with Pinia is that each module you used previously is now a store.
Actions no longer accept context as their first parameters. They should be updated to access state or any other context property directly. The same applies for rootState, rootGetters etc. since the concept of a single global store doesn’t exist. If you want to use another store you need to explicitly import it.
It’s evident that for large projects, migration will be complicated and time-consuming, but hopefully, a lot of boilerplate code will be eliminated, and the store will follow a more clean and modular architecture. The conversion can be done module by module rather than converting everything at once. You can actually mix Pinia and Vuex together during the migration so that this approach can work.
For more information and to develop a website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop a Website using Vue.js, please visit our technology page.
Content Source:
This RFC outlines the biggest update to Next.js since it was introduced in 2016:
The new Next.js router will be built on top of the recently released React 18 features.
This RFC introduces new routing conventions and syntax. The terminology is based on React and standard web platform terms. Throughout the RFC, you’ll see these terms linked back to their definitions below.
URL Path: Part of the URL that comes after the domain.
URL Segment: Part of the URL path is delimited by slashes.
To ensure these new improvements can be incrementally adopted and avoid breaking changes, there is a proposed new directory called app.
The app directory will work alongside the page directory. You can incrementally move parts of your application to the new app directory to take advantage of the new features. For backward compatibility, the behavior of the page directory will remain the same and continue to be supported.
You can use the folder hierarchy inside the app to define routes. A route is a single path of nested folders, following the hierarchy from the root folder down to a final leaf folder.
For example, you can add a new /dashboard/settings route by nesting two new folders in the app directory.
Note: With this system, you'll use folders to define routes, and files to define UI (with new file conventions such as layout.js, page.js, and in the second part of the RFC loading.js). This allows you to colocate your own project files (UI components, test files, stories, etc) inside the app directory. Currently this is only possible with the pageExtensions config.
Each folder in the subtree represents a route segment. Each route segment is mapped to a corresponding segment in a URL path.
For example, the /dashboard/settings route is composed of 3 segments:
The / root segment
The dashboard segment
The settings segment
Note: The name route segment was chosen to match the existing terminology around URL paths.
New file convention: layout.js
So far, the folders are used to define the routes of our application. But empty folders do not do anything by themselves.
A layout is UI that is shared between route segments in a subtree. Layouts do not affect URL paths and do not re-render (React state is preserved) when a user navigates between sibling segments.
A layout can be defined by default exporting a React component from a layout.js file. The component should accept a children prop which will be populated with the segments the layout is wrapping.
There are 2 types of layouts:
Root layout: Applies to all routes
Regular layout: Applies to specific routes
You can nest two or more layouts together to form nested layouts.
You can create a root layout that will apply to all routes of your application by adding a layout.js file inside the app folder.
Note: The root layout replaces the need for a custom App (_app.js) and custom Document (_document.js) since it applies to all routes. You'll be able to use the root layout to customize the initial document shell (e.g. <html> and <body> tags). You'll be able to use data fetching methods inside the root layout (and other layouts).
You can also create a layout that only applies to a part of your application by adding a layout.js file inside a specific folder.
For example, you can create a layout.js file inside the dashboard folder which will only apply to the route segments inside dashboard.
Layouts are nested by default.
For example, if it were to combine the two layouts above. The root layout (app/layout.js) would be applied to the dashboard layout, which would also apply to all route segments inside dashboard/*.
New file convention: page.js
A page is UI that is unique to a route segment. You can create a page by adding a page.js file inside a folder.
For example, to create pages for the /dashboard/* routes, you can add a page.js file inside each folder. When a user visits /dashboard/settings, Next.js will render the page.js file for the settings folder wrapped in any layouts that exist further up the subtree.
You can create a page.js file directly inside the dashboard folder to match the /dashboard route. The dashboard layout will also apply to this page:
This route is composed of 2 segments:
Note: For a route to be valid, it needs to have a page in its leaf segment. If it doesn't, the route will throw an error.
When a layout component is rendered, the children prop will be populated with a child layout (if it exists further down the subtree) or a page.
It may be easier to visualize it as a layout tree where the parent layout will pick the nearest child layout until it reaches a page.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using React JS, please visit our technology page.
Content Source:
Node.js 18.0 is released by the Node.js community. The most wonderful news is that in October 2022, this version will be elevated to long-term support (LTS). The codename for the release will be ‘Hydrogen’ once it is promoted to long-term support. Support for Node.js 18 will last until April 2025.
The most exciting news is that version 18 will finally provide native fetch functionality in Node.js. For the longest time, Node did not contain support for fetch, which is a highly standard API on the web for conducting HTTP requests or any other type of network request, and Node did not support it by default. If you wanted to make an HTTP request, you had to either use third-party tools or write the request from scratch. The implementation comes from undici and is inspired by node-fetch which was originally based upon undici-fetch. The implementation strives to be as close to spec-compliant as possible, but some aspects would require a browser environment and are thus omitted.
The API will remain experimental until further test coverage is introduced and the contributors have verified that the API implements as much of the requirements as is practicable.
Because JavaScript is utilised in so many areas, this is actually wonderful news for the entire ecosystem.It’s utilised on the web, in Node.js, and in Cloudflare workers, for example.
Cloudflare workers are currently shipping with their own proprietary implementation fetch. You’ll ought to install some few packages until you can use Node.There is a version for the web, so there is a lot of inconsistency along the route. Node is now providing formal support for this. That is, any environment that runs JavaScript on servers is almost certainly running Node. If it isn’t running Deno, it will support fetch by default, and because this is the team, the real team, doing it.
If you look at this issue closely, you can see that Node utilised or primarily ported a library called Undici. What exactly is this library? It’s officially produced by the Node team, however it’s really an HTTP 1.1 full-fledged client written entirely in Node JS.
The node:test module facilitates the creation of JavaScript tests that report results in TAP format. To access it:
import test from ‘node:test’;
This module is only available under the node: scheme. __Node Document
Node.js 18 features a test runner that is still in development.It is not meant to replace full-featured alternatives such as Jest or Mocha, but it does provide a quick and straightforward way to execute a test suite without any additional dependencies.
It provides TAP output, which is extensively used, and makes the output easier to consume.
More information may be found in the community blog post and the Node.js API docs
Note: The test runner module is only available using the node: prefix. The node: prefix denotes the loading of a core module. Omitting the prefix and importing ‘test’ would attempt to load a userland module. __Node Documents
As with other major releases, this one upgrades the minimum supported levels for systems and tooling needed to create Node.js. Node.js includes pre-built binaries for a variety of platforms. The minimum toolchains for each major release are evaluated and raised if needed.
Due to issues with creating the V8 dependencies in Node.js, prebuilt binaries for 32-bit Windows will not be accessible at first. With a future V8 upgrade, we hope to restore 32-bit Windows binaries for Node.js 18.
Supported platforms is current as of the branch/release to which it belongs
Node.js relies on V8 and libuv. We adopt a subset of their supported platforms.
There are three support tiers:
The V8 engine has been updated to version 10.1 as part of Chromium 101. The following new features are added in Node.js 17.9.0 over the previous version:
With the findLast() and findLastIndex() methods, This use case is easily and ergonomically solved.They perform identically to their find() and findIndex() equivalents, with the exception that they begin their search at the end of the Array or TypedArray.
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
If you’re building a minimalist product, but want to add an extra level of customisation or expansion, then plugins are a great way to enable that. They allow each instance to be customised with additional code that anyone can create.
In this tutorial, we will extend a minimal web server with a plugin system, create a plugin, and use that plugin with the server. We’ve already created a very basic web server. We’ll use this as our starter code.
But before we start, what is a plugin? A plugin is an extra piece of code that expands what a program can normally do. Web extensions are a good example of this. They leverage existing APIs, and build new functionality upon them. In certain circumstances, they can also be used to patch bugs and flaws that the main software provider has not yet addressed.
In this tutorial, we’ll be building a request counting plugin, and the system to load and unload that plugin.
Let’s start by creating a fresh Node.js project. I’ll be using NPM in this tutorial, but I’ll add the Yarn commands too.
mkdir my-plugin-app
cd my-plugin-app
npm init -y (yarn init -y)
npm i express (yarn add express)
We won’t go through the process of creating an app for our plugins system. Instead, we’ll use this starter code. A simple server with one endpoint. Create an index.js file and add this starter code.
const express = require('express'); const EventEmitter = require('events'); class App extends EventEmitter { constructor() { super(); this.server = express(); this.server.use(express.json()); } start() { this.server.get('/', (req, res) => { res.send('Hello World!'); }); this.server.listen(8080, () => { console.log('Server started on port 3000') this.emit('start'); }); } stop() { if (this.stopped) return; console.log('Server stopped'); this.emit('stop'); this.stopped = true; process.exit(); } } const app = new App(); app.start(); ["exit", "SIGINT", "SIGUSR1", "SIGUSR2", "SIGTERM", "uncaughtException"].forEach(event => { process.on(event, () => app.stop()); });
To get a sense as to what our plugin system will do, let’s create a little plugin containing everything a plugin will need. The type of plugin system we’ll be implementing has two events. load and unload are the two times we will directly call any code in the plugin. load sets up any extra routes, middleware or anything else that is part of the plugin, and unload tells us to safely stop whatever we’re doing and save any persistent data.
This plugin will set up a middleware to count the number of requests we get. In addition, it will add an API route so we can query the number of requests that have been made so far. The plugin will export two different functions, one for each event.
const fs = require('fs'); let count = 0; function load(app) { try { count = +fs.readFileSync('./counter.txt'); } catch (e) { console.log('counter.txt not found. Starting from 0'); } app.server.use((req, res, next) => { count++; next(); }); app.server.get('/count', (req, res) => { res.send({ count }); }) } // Save request count for next time function unload(app) { fs.writeFileSync('./counter.txt', count); } module.exports = { load, unload };
Our plugin system will all be kept in a separate class from the main app, we’ll put this in a new file plugins.js. The point of this class is to load and unload plugins.
The load function takes a path to a plugin file, and uses the require method to load it during runtime. The loadFromConfig method allows us to load plugins defined in a config file.
const fs = require("fs"); class Plugins { constructor(app) { super(); this.app = app; this.plugins = {}; } async loadFromConfig(path='./plugins.json') { const plugins = JSON.parse(fs.readFileSync(path)).plugins; for (let plugin in plugins) { if (plugins[plugin].enabled) { this.load(plugin); } } } async load(plugin) { const path = plugins[plugin]; try { const module = require(path); this.plugins[plugin] = module; await this.plugins[plugin].load(this.app); console.log(`Loaded plugin: '${plugin}'`); } catch (e) { console.log(`Failed to load '${plugin}'`) this.app.stop(); } } } module.exports = Plugins;
We’ll use a plugins.json file to store the paths to all the plugins we wish to load, then call the loadFromConfig method to load them all at once. Put the plugins.json file in the same directory as your code.
{ "counter": "./counter.js" }
Finally, we’ll create an instance of the plugin in our app. Import the Plugins class, create an instance in the constructor, and call loadFromConfig leaving the path blank (the default is ./plugins.json).
const express = require('express'); const Plugins = require('./plugins'); class App { constructor() { super(); this.plugins = new Plugins(this); this.server = express(); this.server.use(express.json()); } async start() { await this.plugins.load(); this.server.get('/', (req, res) => { res.send('Hello World!'); }); this.server.listen(8080, () => { console.log('Server started on port 3000') }); } stop() { if (this.stopped) return; console.log('Server stopped'); this.stopped = true; process.exit(); } } const app = new App(); app.start(); ["exit", "SIGINT", "SIGUSR1", "SIGUSR2", "SIGTERM", "uncaughtException"].forEach(event => { process.on(event, () => app.stop()); });
We now need to handle the unload method exported from our plugin. And once we do, we need to remove it from the plugins collection. We’ll also include a stop method which will unload all plugins. We’ll use this method later to enable safe shutdowns.
const fs = require("fs"); class Plugins { constructor(app) { super(); this.app = app; this.plugins = {}; } async loadFromConfig(path='./plugins.json') { const plugins = JSON.parse(fs.readFileSync(path)).plugins; for (let plugin in plugins) { if (plugins[plugin].enabled) { this.load(plugin); } } } async load(plugin) { const path = plugins[plugin]; try { const module = require(path); this.plugins[plugin] = module; await this.plugins[plugin].load(this.app); console.log(`Loaded plugin: '${plugin}'`); } catch (e) { console.log(`Failed to load '${plugin}'`) this.app.stop(); } } unload(plugin) { if (this.plugins[plugin]) { this.plugins[plugin].unload(); delete this.plugins[plugin]; console.log(`Unloaded plugin: '${plugin}'`); } } stop() { for (let plugin in this.plugins) { this.unload(plugin); } } } module.exports = Plugins;
To make sure that plugins get a chance to unload when the app closes, we need to call Plugins.stop. In the index.js code, we included a stop method that gets called when the app is killed, and we’ve just added a stop method to the Plugins class. So let’s call the Plugins.stop method when our app stop method is called.
Add the following to the App.stop method.
stop() { if (this.stopped) return; + this.plugins.stop(); console.log('Server stopped'); this.stopped = true; process.exit(); }
For more information and to develop web applications using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Node JS, please visit our technology page.
Content Source:
The new release of Google’s popular TypeScript-based web framework is available now.
This post will bring you closer to the most important new features and breaking changes in Angular 13 and help you decide whether an update for your project is worthwhile.
Angular has introduced its next-generation compilation and rendering pipeline Ivy since its version 8. Angular 9 has used Ivy by default while maintaining support for the predecessor compiler and runtime View Engine.
The new version of the framework is now 100 percent Ivy.
To streamline and modernize the Angular Package Format (APF), View Engine specific metadata and older output formats are now removed, which will reduce maintenance costs and the complexity of the codebase in Angular 13. All internal tools are converted to Ivy beforehand so that the change should work smoothly.
Ivy compiles individual components more independently of one another, which improves development times. The use of ngcc (Angular compatibility compiler) is no more required for libraries built with the latest version of the APF. This will offer a faster execution for libraries developers.
The load time is reduced in Angular 13 with the help of ergonomic code-splitting APIs and granular code breakdown at a component level.
A performance improvement was also achieved with the introduction of ESBuild, an extremely fast JavaScript bundler. ESBuild works now with terser to optimize global scripts and supports CSS sourcemaps, which enables optimized global CSS.
ESBuild also supports other framework languages like Elm, Svelte, and Vue.To benefit from native web APIs and modern browser features such as web animations and CSS variables, the Angular team has removed the Internet Explorer 11 support.
This offers a smaller bundle size and faster load for apps and an improved user experience because of the absence of IE-specific polyfills and the no need for differential loading.
This breaking change will certainly affect authorities or institutions that still use IE 11 and have not yet switched to Microsoft Edge or other modern browsers.
You can now create dynamic components with less boilerplate code thanks to an improvement of ViewContainerRef.createComponent API.
Here is the old way of creating a dynamic component:
export class InquiryDialog implements OnInit { componentRef: ComponentRef; @ViewChild('inquiryPage', {static: true, read: ViewContainerRef}) container: ViewContainerRef; constructor(@Inject(MAT_DIALOG_DATA) public data: InquiryDialogData, private componentFactoryResolver: ComponentFactoryResolver) {} ngOnInit(): void { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.data.inquiryPageComponent); this.componentRef = this.container.createComponent(componentFactory); } }
And with Angular 13, there is no need to use ComponentFactoryResolver:
export class InquiryDialog implements OnInit { componentRef: ComponentRef; @ViewChild('inquiryPage', {static: true, read: ViewContainerRef}) container: ViewContainerRef; constructor(@Inject(MAT_DIALOG_DATA) public data: InquiryDialogData) {} ngOnInit(): void { this.componentRef = this.container.createComponent(this.data.inquiryPageComponent); } }
Angular 13 way of creating a dynamic component
TestBed is the primary unit tests API for Angular applications and libraries.
In order to decrease the test time in TestBed, the new version is released with an improved test API. The framework can now set up and tear down the test environment and learn the DOM automatically after each test run. This leads to faster, less memory-intensive, and better-isolated tests.
Angular 13 has introduced a new type for forms, which is FormControlStatus. It’s a union of all possible status strings for form controls:
There is an Accessibility (A11y) improvement in Angular Material: all Material Design Components (MDC) have been checked for better Accessibility.
Checkboxes and radio buttons, for example, have now larger touch sizes, and other components have better high contrast modes.
A comparison of touch target sizes. The sizes on the right are the new sizes.
For more information and to develop web applications using Angular, Hire Angular Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Angular, please visit our technology page.
Content Source:
Angular keeps growing in adoption and keeps becoming every day more popular among Frontend implementations.
In this brief guide, we will have a look around some of the greatest and most popular UI kits and frameworks, trying to understand which one of those could be the right choice for your next project.
Angular Material is considered today one of the most popular UI kit for Angular, probably the most one, despite its root feature that makes it anchored to the material design style, which could be not good for everyone. With more than 22k stars on GitHub, this kit is proving its so much beloved by developers and guarantees good community support that keeps posting and discussing bugs, features to integrate, eventually performances issues, and more.
Good to develop a CRM or an admin software, very bad for general-purpose Front end needings. Still missing good documentation and the material look-and-feel could not be good for everyone. Found it very stable: use it and don’t pretend to customize it a lot, because despite the CDK it will drive you mad as hell.
Defined as “Bootstrap widgets — The angular way” by its authors, the Ng-bootstrap UI kit has been popular for a lot and was one of the first kits available around.
The anthem has been “let’s replicate Bootstrap features and make them all available to Angular”. The result is a good basic UI kit without complaints, but really essential. Some components are a bit inadequate compared to the original ones and the documentation is very concise. A good choice if you need the “basic bootstrap”, but not much more.
Ng-bootstrap is a good kit if you need plain Bootstrap features, not useful if you need more. Today it’s suffering the Ngx library as a rival, but Ngx is more complete, newer, and even more professional in some cases, so let’s choose this if you don’t need much.
This recent UI kit designed by Valor Software is becoming rapidly popular and lives on the “Develop faster and better” motto. Could sound like an Ng-bootstrap clone and it could be considered something similar, but the truth is that this one is completely redesigned and provides better features and advanced components.
Supports Bootstrap 3, 4, and even the 5th version proving that this library provides a good supporting community and that is often updated.
To me, Ngx is the best Bootstrap-based UI Kit. Very solid, very comprehensive documentation, and never had issues. Consider this one to be the basic standard for modern web apps. If you miss something, just integrate. This is a real bootstrap to me.
Yet another Bootstrap-based UI kit, MDBootstrap is a HUGE kit and is almost the quintessential of UI components for Angular, providing really everything for any need.
It’s the only one that comes with a CLI, premium support, and which looks like a “professional” tool. But other than that the result is not much satisfying. I found it really messy, really heavy, and hard to set up.
I’ve had a brief experience with this and it just didn’t fit my needings. Could be a good choice if you want to invest some time to really understand it and to adopt it as a “company standard” development process, not really suited for spare developers or Open source projects. Too complex and too less immediate, it feels like working with a “big Java framework” more than a UI Kit for angular.
The IBM’s solution for Front end needings: this UI kit looks enterprise, professional, and even beautiful. Carbon didn’t become a real breakthrough in the UI kits panorama and competition, but it’s worth trying.
The documentation is superb, covering really a lot of aspects about components implementations.
The Carbon IBM’s solution looks very fascinating and charming but must be considered an advanced tool which could not suit your needings. There are many projects where you really don’t need that much technique and its complexity will force you to spend some hours to really understand approaches and mechanisms. Give it a try if you need an enterprise tool.
For more information and to develop web applications using Angular, Hire Angular Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop your custom web app using Angular, please visit our technology page.
Content Source:
Organic traffic is a great way to get eyeballs on your website and Google is the most popular search engine of choice that you can use to get that organic traffic coming.
Although Google ranks your site based on a lot of metrics, how fast your website loads is one of the critical factors.
Websites that load quickly are not just great for rankings but also for the overall user experience.
Since most of us developers( especially indie developers) are using JavaScript frameworks, such as React and Angular, which probably do a client-side rendering of data, the speed at which data is fetched forms an important aspect of the development process.
There is a simple way of making your site load faster, and that is caching and CDN(Content Delivery Network).
Using a combination of both can lead to miraculous drops in time taken to load the first byte.
In this blog, I will demonstrate caching with an example using Redis and also explain what is CDN.
Caching, in layman’s language, is storing data that you think might be used frequently into memory(called cache).
So the next time you need that data, you check whether it’s stored in the memory and if not, then you make a call to the database to fetch it and maybe store it into the cache for future use.
As you can see from the image above, caching is simply a layer of a data structure containing frequently accessed data between your data source and the app.
Not all data needs to be cached. For example, a user’s personal setting or shouldn’t be cached on the server. However, you can always store them in the client’s local storage for faster access.
Caching of data is one of the simplest ways to reduce the load time, at the same time, you have to be smart about how you cache your data.
As stated before, frequently accessed data should be cached to provide a responsive and quick experience.
Different developers have different caching strategies depending on their preferences and needs. If you want me to cover various common caching strategies, then drop a response to this blog.
Below are some examples of items that you should cache:
Authorization & Session Tokens
Landing page data that doesn’t change often(such as recent projects in a portfolio site).
Blog and post drafts can be stored in cache for a while and then inserted into the database after a fixed amount of time.
Real-time comment streams & analytics.
Although you are free to use whatever option you are comfortable with, I highly recommend at least checking Redis out.
Redis is an open-sourced in-memory data structure store that has familiar data types such as lists, dictionaries, strings, hashes, etc.
It is a key-value data store with extended abilities such as the ability to set expiry dates.
Redis is the most loved database as per the Stack Overflow 2021 survey.
AWS’s MemoryDB for Redis is a great choice if you need a durable transactional log that stores data across multiple Availability Zones.
Installing Redis is incredibly straightforward if you are on Linux.
Head over to the Redis download page and download the latest stable version available or you can simply run the following command in your terminal:
sudo apt-get install redis
Once you are done installing Redis, simply type redis-server to spin up a Redis server. The default port of this server is port 6379.
However, if you are on Windows, there are two options.
You can either follow the simple guide on how to install an outdated Redis on your Windows machine or you can use Windows Subsystem for Linux(WSL) and get the latest Redis.
I personally went with the WSL way and it created an Ubuntu 20.04 system for me to install Redis and any other packages I might need in the future.
There are plenty of guides available online on how to get started with Redis, hence I will just be providing a demo of what Redis can do to speed up your website.
I will be creating a simple Node.js server that fetches some data from the web and then sends them to its clients and later we will be adding caching to it and see the massive difference.
Below is a server that simply fetches the data from a data source and then passes it along to the client.
const express = require('express'); const app = express(); const redis = require('redis'); const fetch = require('cross-fetch'); const cacheClient = redis.createClient(); app.get('/', async (req, res, next) => { await fetch('https://jsonplaceholder.typicode.com/photos') .then(response => response.json()) .then(json => { console.log('Newly fetched data') return res.json({ data: json }); }) }); app.listen(3000, () => console.log('listening on port 3000'));
You can see the response time in the image attached below:
Now we will implement caching using Redis.
First of all, we need an npm package.
npm i --save redis
Once this is installed, we will import it into our server.js file & create a client.
const redis = require('redis'); const cacheClient = redis.createClient(); // => Redis client
We need to edit our app.get() function and add caching logic to it.
It’s simple if-else logic. We first check if the data is present in our Redis server or not by calling the Redis client and using the .get() to get data.
If the data is not present, then we make a call to our data source to get fresh data. We insert this data into our Redis store by calling the .setex() function on our Redis client.
cacheClient.setex('sample',60,JSON.stringify(json));
The first parameter is the name(key) of the data we want to store, followed by the time to expire, and then finally the actual data(value) goes in as the third parameter.
We are using JSON.stringify() method to convert our JSON data to a string data type.
With the data stored in the Redis store, the next time the app.get(‘/’) function is called, the client will be able to fetch the data from the Redis server instead of fetching from our original data source.
With this implemented, we can instantly see amazing results as the time taken is just 52ms compared to 1301ms from before.
This was a very simplistic view of caching and Redis is capable of much more than caching and can even be used as a permanent storage option.
Our final server.js file will look like this:
const express = require('express') const app = express(); const redis = require('redis'); const fetch = require('cross-fetch'); const cacheClient = redis.createClient(); app.get('/', async (req, res, next) => { await cacheClient.get('sample', async (err, data) => { if (err) console.error(err); if (data) { console.log('Data was cached before') return res.json({ data: JSON.parse(data) }); } else await fetch('https://jsonplaceholder.typicode.com/photos') .then(response => response.json()) .then(json => { console.log('Newly fetched data') cacheClient.setex('sample', 60, JSON.stringify(json)); return res.json({ data: json }); }) }) }); app.listen(3000, () => console.log('listening on port 3000'));
Caching data on the server is surely a great improvement but what about caching large HTML, video & image files?
CDN provides a simple solution to this issue. It is important to know that CDN and caching are not the same.
While CDN does cache content, not everything that cache data can be called a CDN.
CDN refers to a geographically distributed group of servers that work together to provide fast delivery of sites & other assets(like image & video files).
Popular sites such as Netflix and Facebook leverage the benefits of the CDN and deliver content quickly to you using the nearest group of servers near you.
CDN stores a cached copy of your content in multiple locations throughout the world.
So if someone from Australia visits your UK-hosted site, they will instead visit the nearest CDN server available to Australia and get a cached copy of your UK-hosted site.
This also saves bandwidth costs and increases reliability & uptime.
In some platforms and hosts, a CDN is at your disposal by default, and generally, using it is as simple as adding a header to your HTML file.
Personally, in my experience, I have found Vercel’s CDN to be the simplest to use with a good, detailed guide with a useful feature that prevents your data from being stale(outdated).
In Vercel, you just need to add a header to inform the CDN that the site needs to be cached. An example header is given below:
Cache-Control: s-maxage=1
It is worth noting that any data that you load client side will not be included in your site’s cached CDN copy. This is because the data is loaded dynamically on the client-side and not server-rendered.
However, you can always cache the data that is being loaded on the client-side via Redis, CDN, or any other option available to make the dynamic loading faster.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
As the world leans more towards digital technologies, as more businesses focus on online and physical presence, and as content continues to dominate, web development becomes even more essential.
Accordingly, one of the best programming languages for better frontend development is JavaScript. That’s why, today, we want to show you some of the top JavaScript trends that can help boost your web application’s success.
Dark mode has been one of the recent web development trends that have been blowing up everywhere. As a result, almost all popular apps can switch to a dark mode or stick with the standard light mode.
Moreover, since it uses less color and brightness, the dark mode also helps preserve the battery and makes it last longer. Some people also claim that dark selection can be beneficial for specific visual impairments. For web designers, the dark mode also allows them to use colors more creatively, as the black background of the dark option can help colors stand out even more.
Using this script snippet results in the widget appearing on your site automatically so that users can conveniently switch between their preferred themes. The plugin is relatively lightweight, and since it uses local storage, it will remember and save the last chosen theme.
Another JavaScript trend that remains on top for a few years and is gradually garnering more popularity is React.js. React is an open source, frontend, and entirely free JavaScript library for developing smooth and effective user interfaces, especially for single-page apps.
Facebook developed the React library several years ago and has built it into one of the most popular JavaScript libraries for frontend developers. In 2020, 80% of front-end developers were using React only. In addition, many companies like WhatsApp and Airbnb have taken on this library as well.
The reason behind this is that React offers a lot of convenience and benefits for today’s developers. The programming library is easy to learn and even easier to use. It comes with many tutorials and documents explaining how to utilize the library best.
If you are already skilled in JavaScript, picking up React will be no trouble at all, and you will find yourself easily using it within a few days. React also comes with a lot of reusable components, which are a lifesaver for any developer.
The JavaScript framework uses small user interface components, which you can use to create more prominent parts or reuse again to save your time and efforts. All the pieces have their logic, and they can control their rendering, which allows you to use them again wherever and whenever you need them quickly.
Convenience is important to me. It helps me navigate the flow more efficiently. How about you?
All this makes it easy to develop and maintain apps. In addition, since you are reusing the same essential components, you can keep your projects’ same feel and look. Other popular libraries besides React include Angular, Vue, and Svelte.
A better user experience does not just include a smooth and fast website. It also contains a unique and creatively designed website and what better way to show off your creativity than through animations.
Animations can make your website visually striking and keep visitors hooked on your page. They can help differentiate your website from all the usual static websites. If you think you need to go out and do some special courses on animation, we’ve got some good news.
JavaScript has several libraries that allow you to integrate animations on your website easily. These libraries include anime.js and JSTweener. You can input these into your website code, customize the code, and voila! Your animations are ready.
Especially if you are running a business or have a product checkout page on your website, employing data visualization tools can significantly help you in many ways. First, it can improve the user interface and experience by filling out fields quickly and accurately.
As a result, the whole checkout experience for visitors and potential customers becomes much more accessible and makes them more willing to follow through on their purchases. Due to all these benefits, data visualization is a big trend within JavaScript for business and marketing purposes.
All you need is a little <input />
One specific library that is quite useful is Algolia Places. It allows you to create much more efficient forms, which help inaccurate data input and quick form filling. In addition, you can incorporate a map that will conveniently display a specific location for better data visualization.
Algolia Places uses OpenStreetMap’s extensive database and is incredibly fast to use. In addition, it can handle some typing mistakes and simplifies the entire checkout process for users.
Incorporating full-screen videos on your webpage is one of the most popular JavaScript trends developers utilize these days. Again, rather than creating an essential static website, incorporating dynamic videos and GIFs can help make your website more interactive and offer a better user experience.
A better user experience, then, can help drive more traffic to your website, making it easy to push your content, raise awareness about your brand and increase your ROI for your marketing and business objectives. But, how can you add full-screen videos to your website?
JavaScript offers a great resource: Bideo.js. This library makes it super easy to add full-screen videos to your website’s background. While it takes a while to load, you do not have to write endless code to incorporate the video smoothly.
The library has everything you need to add the videos along with several customization options quickly. The code works great for screens of all sizes and various platforms as well. This JavaScript tool can help play high-quality and engaging videos smoothly in the background, whether a computer or mobile. You can resize the video according to the browser, and it is also easy to implement using CSS or HTML.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
JavaScript is a very powerful programming language these days. There is a lot that you can do with it. In addition to that, JavaScript has a huge ecosystem that allows you to discover a lot of useful tools, frameworks, and libraries.
JavaScript has a lot of powerful features and tools that make the life of the developer much easier. The syntax contains a lot of shorthands that you can use to write JavaScript code much faster and reduce lines. Especially in the latest ECMAScript specifications.
In this article, we will give you a list of shorthands that you can use in JavaScript. So let’s get right into it.
Normally, to convert a string to a number, we use the method parseInt() . However, there is a shorthand that allows us to do that.
By using the unary operator + , we can easily convert a string into a number.
Here is an example:
let speed = "60"; console.log(typeof speed); //string console.log(typeof +speed); //number console.log(+speed); //60, not "60".
As you can see, only by adding + at the beginning of the variable speed , we were able to convert the speed to a number.
There is also another shorthand to convert from a number into a string. It’s by simply adding an empty string to the number.
Here is an example:
let speed = 100; speed += ""; //returns "100" , not 100. console.log(typeof speed); //string
Another shorthand is the ternary operator, it allows us to easily write conditional statements in a short way using the keywords ? and : .
Here is an example using IF else statements:
Longhand:
let speed = 80; if(speed < 30){ console.log('slow'); }else if(speed > 60){ console.log('fast'); }else{ console.log('between 30 and 60'); } //output: fast
Here is the same example, but now using the ternary operator instead:
Shorthand:
let speed = 80; console.log(speed < 30 ? 'slow': speed > 60 ? 'fast' : 'between 30 & 60'); //output: fast
As you can see, by using the ternary operator shorthand, we were able to easily reduce the amount of code we had to write. It only took us 2 lines of code to write the conditional statements.
Have a look at the below example using an IF statement.
Longhand:
let isOnline = true; if(isOnline){ console.log("Online"); } //returns "online"
We can write the same statement using the short circuit && . Here is the example:
Shorthand:
let isOnline = true; isOnline && console.log("Online"); //returns "online"
The short circuit evaluation && is one of the shorthands that allow you to write short conditionals. It’s used between two values, if the first value is truthy, it returns the second value. Otherwise, it returns the first value.
The best shorthand to flatten a multidimensional array is by using the method flat(). We have seen, a lot of developers use the method filter, concat, and all other long ways to flatten an array. Maybe because they don’t know about the flat method yet.
So this amazing method allows you to flatten an array in one single line of code. It accepts one optional argument(number), which is the level of flattening(how deep you want to flatten an array).
Here is an example:
let numbers = [9, [102, 5], [6, 3], 2]; numbers.flat(); //returns [9, 102, 5, 6, 3, 2]
When it comes to merging and cloning arrays in JavaScript, the spread operator {…} is the best shorthand you can use.
Merging arrays:
const employees = ["Chris", "John"]; const entrepreneurs = ["James", "Anna"]; //merging both arrays to a new array. const all = [...employees, ...entrepreneurs]; console.log(all); //output: ["Chris", "John", "James", "Anna"]
Cloning an array:
const numbers = [4, 8, 9, 0]; //cloning the numbers array. const clone = [...numbers]; console.log(clone); //output: [4, 8, 9, 0]
Mostly when we want to loop through an array using a for loop, we do it like this:
Longhand:
const users = ["John", "Chris", "Mehdi", "James"]; for(let i = 0; i < users.length; i++){ console.log(users[i]); } /*output: John Chris Mehdi James */
But we can achieve the same thing using the loop for of shorthand:
Shorthand:
const users = ["John", "Chris", "Mehdi", "James"]; for (let user of users){ console.log(user); } /*output: John Chris Mehdi James*/
Arrow functions are a shorthand that allows you to easily write functions in a short way and reduce your code.
Here are the examples:
Normal function:
function addNums(x, y){ return x + y; } addNums(6, 5); //11
Arrow function:
const addNums = (x, y)=> x + y; addNums(6, 5); //11
As you can see, these are some of the popular shorthands that you can use in JavaScript. They allow you to reduce code syntax and keep your code short as much as you can.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
We always say that JavaScript is full of surprises. It never fails to amaze us. Every day, we learn something new about this programming language. Something which is very small but can make a huge impact on your code. Something which is worth sharing.
In this article, we’re going to share eight JavaScript hacks that you can use in your day-to-day stuff. So let’s learn something new!
It’s very common to use event listeners in your web app, not just in Vanilla JS applications, but also in modern JS frameworks and libraries like Angular and React.
To cite an example, let’s say we want to do something on a button click. We can use event listeners here. Often, we want to act whenever a specific event fires. But what if we want to do it only once?
Not to worry. We can actually execute our event listeners only once by simply doing this:
const button = document.querySelector('button'); button.addEventListener('click', () => { console.log('We will only run once'); },{ once: true })
To be honest, all of us have faced a situation where we felt like our web application is getting slower and we are not able to find out why. We’ve felt like we are doing everything as it should be, but still the browser is taking time to show the first content of our application.
Well, this might be because of long scripts getting executed before HTML. Often, we add our scripts inand we forgot that the next statements will not be executed until the script in <HEAD> finishes its execution.
We can simply use the defer attribute with our scripts to execute them after the HTML content.
/* No matter where you place this script tag inside the HTML, this will only run when the HTML content is completely loaded. */ <script src="main.js" defer></script>
It’s always recommended to use shorthand to make our code look cleaner. As no application can survive without conditionals like the if statement, we should know the shortcuts for that, too. And thankfully, JavaScript provides the && operator.
We can shorten our conditional checking by using the && operator.
let condition = true; // Long way if (condition) { someFunction(); } // Short way condition && someFunction();
We can simply generate a random number from a given range with just one line of code. These kinds of tricks are very useful in real-world applications.
function randomNumber(num1, num2) { return Math.random() * (num2 - num1) + num1; } console.log(randomNumber(50, 100)); // Expected output - random number between 50 and 100 (50 and 100 will be inclusive)
This is one of the hacks which We love the most. We can empty an array just by giving the value 0 to its length property.
let sampleArray = ["John", "Bob", "Mark", "Alex"]; sampleArray.length = 0; console.log(sampleArray); // Output - [] (it's empty now)
We can use the Object.entries() method to check whether an object is empty or not. Since Object.entries() returns the array of the object’s enumerable properties, therefore if the length of that array is 0, that means the object is empty such that the object has 0 property.
let sampleObj = { name: "Mark", occupation: "Developer" }; let emptyObj = {}; console.log(Object.entries(sampleObj).length === 0); // false console.log(Object.entries(emptyObj).length === 0); // false
From ES6, we have a new concept in JavaScript which is called Set.
"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." — MDN Docs
Since Set in JavaScript is a collection of items that are unique, i.e., no element can be repeated, therefore we can use it to filter duplicate values from an array.
This trick is again very simple but very useful. First, we will convert our array into Set, and as Set doesn’t have duplicate values, our new Set will have unique values from our array. Then we simply convert this new Set back into an array.
let namesArray = ["John", "Bob", "Mark", "Alex", "Mark", "Alain", "Bob"]; console.log([...new Set(namesArray)]); // Output - ["John", "Bob", "Mark", "Alex", "Alain"]
Since objects in JavaScript are reference types, we can’t simply use = to clone them, so with the below three methods, you can properly clone an object using just one line.
const person = { name: "Mark", username: "@markcodes" }; // Using Object.assign() Method const clonePerson1 = Object.assign({}, person); // Using JSON const clonePerson2 = JSON.parse(JSON.stringify(person)); // Using Spread Operator const clonePerson3 = { ...person };
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2025 — HK Infosoft. All Rights Reserved.
© 2025 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap