Sunday, October 4, 2020

Docker in Azure

What is Azure Container Instances

Azure Container Instances (ACI) allows us to deploy individual containers in Azure without having to provision Virtual Machines.

It is kind of a serverless computing environment where we can deploy our applications as Docker containers in Azure Container Instances. 

Creating an Azure Container Registry (ACR)

 We can create an Azure Container Registry (ACR) in different ways, using Azure CLI or Azure Portal or Powershell. In this post, we shall see how to create an Azure Container Registry using Azure CLI. 

The first step in creating an Azure Container Registry (ACR) using Azure CLI is to log in to Azure CLI. Open a command prompt and enter the command.

What is Azure Container Registry?

 Azure Container Registry is like a private DockerHub in Azure. It is a managed private Docker registry service based on the open-source Docker Registry 2.0. Create and maintain Azure container registries to store and manage your private Docker container images and related artifacts.

We can configure to push the docker images into Azure Container Registry. Familiar tools such as Azure DevOps and Jenkins CI/CD pipeline can be configured to use Azure Container Registry as a build endpoint. 

Azure CLI

 Azure CLI (Command-line Interface) is a command-line tool for Manager azure services. It's like Angular CLI, it provides various commands to manage Azure services in an Account. Before we can start using Azure CLI we need to install it, the latest version of Azure CLI can be installed from the following site.

https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest

Once Azure CLI is installed run the az --version command to make sure that the installation was done successfully. 

Thursday, October 1, 2020

Docker in Visual Studio

Create Docker Image with .Net Core executable

 In the previous post we saw how to create an Executable (.exe file)  for a .Net Core console application. In this post we shall see how to package this .exe into a Docker image and deploy it as a Docker Container. 

First we will have to create a Dockerfile, we will create this file in the publish folder where the publish results (.exe files) are created.    

Creating Executable from .Net Core Application

.Net Core applications by default will create .dll executables, in this post we shall see how to explicitly create a .exe using .Net Core, in the next post we will see how to use this .Exe and create a Docker image. 
Let’s start by creating a .Net Core Console App using Visual Studio.

Monday, September 28, 2020

Updating Dockerfile and rebuilding images using VisualStudio

 In the previous post we saw on how to create a .Net Core console App and use Visual Studio to automatically add Dockerfile to the project. In this post, we will see how to change the Dockerfile created by Visual Studio and rebuild the Docker image with the modified file.

Once the Dockerfile is created we can manually exit the Docker file Add/Modify steps and rebuild the Docker image.

In this sample, we will add proxy settings to enable package restore in a Corporate firewall environment.

Create Dockerfile and Container using Visual Studio

 Visual Studio provides an option to automatically add Docker support. Using Visual Studio we can add the Dockerfile to a project without having to manually create one. Visual Studio will create the Dockerfile with the commands pre-populated based on the type of project, we create. 

In this post, we will create a Console application using .Net Core and use Visual Studio to automatically create the Dockerfile for the Project. First, let us create the following Console application.

Docker Getting Started

Friday, September 25, 2020

Building an ASP.Net Core Web App Docker image

 In this post we shall see how to create a basic Asp.Net core Hello World App and package it into a Docker image. We will deploy the image as a Docker container and execute the Asp.Net Core application from Docker.

First let us start by creating an Asp.Net Core application using Visual Studio 2019

Building a Node App Docker image

 In the previous post we saw how to build a HelloWorld Docker image, in this post we will create a Docker image for a Node.js application.

First let us create a basic Node server using Express which will respond with a Greeting message in the root path (/).

Building a HelloWorld Docker images

 We have seen how to pull a Docker image from DockerHub and run in, now we will see how to create our own Docker image, build and run it.

The first step to create a Docker image is to create a Dockerfile.
Dockerfiles is a text file that contains instructions and steps to create a new Docker image.

A Dockerfile has no extension. If you are using docker on windows use notepad to create a dockerfile while saving select "All type" and save the file name as "Dockerfile".

Friday, September 18, 2020

Listing and Removing Docker Images

In the previous post we saw on how to pull and run Docker Images from a remote repository. Once we pull a Docker Image, it gets stored in the local repository. We can use the image ls command to view the list of images in the local repository.

Listing and Removing Docker Containers

Docker supports a set of commands to operate on Docker Containers. It supports commands to list Containers, Remove containers etc. Below are some of the commonly used commands for Docker Containers.

Pulling Docker Images

In the previous post we executed the docker run command and noticed that the Docker Engine automatically pulled the hello-world image from DockerHub. We can also use the docker pull command to explicitly pull Docker images from the remote repository (DockerHub) to our local DockerRepository.

To pull images from the remote repository to the local repository we need to use the docker pull command as follows.

Running first Docker Container

Once we install Docker and make sure it is up and running we can start running our first Docker Container. Let us run the hello-world Docker container, this container is present in the DockerHub. We will use the docker run command to run the container as follows.

Monday, September 14, 2020

Docker Desktop

 Depending on the version of Windows operating system, we need to either install the Docker Toolkit or Docker Desktop. For Windows version less than 10, we cannot install Docker Desktop for these versions we need to install Docker Toolkit. For Windows 10 we can install Docker Desktop. It is recommended to install Docker Desktop.

Once Docker Desktop is installed, it will start and we can see an icon in the Toolbar.

Installing Docker

 To get started with using Docker we need to download and install the Docker setup. Docker can be installed in multiple platforms Windows / Mac / Linux. We can get the appropriate version of Docker from the below link and install it to get started.

https://docs.docker.com/get-docker/

Friday, September 11, 2020

Docker Overview

What is Docker Network?

 As the name suggests Docker network allows docker containers to communicate with other containers and with the outside world. Docker supports different types of Network configuration depending on the name of the Application / Docker container setup.

Monday, September 7, 2020

What is Docker Engine?

 The Docker Engine is the heart of the Docker platform, it consists of 2 main parts.
                The Client side (Docker CLI & Rest API) is used to fire commands
                The Server side (Docker Daemon) is used to process the commands and manages Containers.

What is Docker Hub?

 Docker Hub is a service provided by Docker for finding and sharing container images. It allows us to push new images and pull existing images from the Hub. DockerHub is like GitHub we can user push/pull commands to manage Docker images. GitHub allows us to store and version controls our source code, while DockerHub allows us to store and version control Docker Images

DockerHub is the default registry used by the Docker engine. DockerHub hosts public and private repositories, it also provides automated builds, organization accounts, and integration with source control solutions like Github and Bitbucket. 

What is Docker Registry?

A Docker Registry is a storage and distribution system for named Docker images. The Docker registry is used to store the static Docker image templates. The same image might have multiple different versions, identified by their tags. 

A Docker Registry is organized into Docker repositories, where a repository holds all the versions of a specific image. The registry allows Docker users to pull images locally, as well as push new images to the registry. 

DockerHub is the default registry used by the Docker engine, it is the Docker's public registry instance. It is possible to run on-premise the open-source Docker registry/distribution, as well as a commercially supported version called Docker Trusted Registry

Sunday, September 6, 2020

What is Docker Daemon?

 The Docker Engine has a client-server setup where can client can fire commands and the Server processes the commands to create and maintain live Docker Containers.

Docker Daemon is the server-side of the Docker Engine, all running Docker Containers are managed by the Docker Daemon. Docker CLI and API are the client-side of the Docker Engine which sends commands to the Docker Daemon. A daemon can also communicate with other daemons to manage Docker services.



What is a Docker Image?

 A Docker Image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries, and settings. A Container image is a static template version of a Docker Container, it is stored in the Docker registry. 

Container images become containers at runtime and in the case of Docker containers - images become containers when they run on Docker Engine.

When we execute the $ docker run command the container image is fetched from the registry and loaded in the Docker Daemon server to make it a live executing container.

Thursday, September 3, 2020

What is a Docker Container?

When we develop an Application and move it between various environments QA, Staging, Production etc, we need to take care of various environmental factors like Operating System version, security patches, network configuration etc. When there is any deviation in these settings the application starts behaving differently and becomes difficult to identify the cause.

Containers help us make this easier, Containers are an abstraction at the app layer that packages code and dependencies together. A Container packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.

Multiple containers can run on the same machine and share the OS kernel with other containers, each running as isolated processes in userspace. Containers take up less space than VMs.

Docker Container vs Virtual Machine

A Virtual Machine is an image that runs on top of a physical server. We can create multiple Virtual Machines on top of a physical server. Each Virtual Machine needs a Guest operating system to function, this makes is heavier since each Guest OS needs Memory, Disk, and CPU to operate. 

A Docker Container can be seen as the next version/improvement to a Virtual Machine. Each Virtual Machine in a server needs a separate Guest operating system to function, but all the Docker Containers in a server use the same underlying Operating System of the server, hence Dockers are lightweight when compared to Virtual Machines. Also, Dockers are faster to spin up and execute when compared to Virtual Machines.

Since each Docker containers don’t need a separate Operating System we can spin up many Docker Containers in a server then the number of Virtual Machines it can handle.

What is Docker?

Docker is an open platform to create, deploy and run applications by using Containers. Docker makes is easy to deploy applications from one environment to another. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and deploy it as one package.

Docker can be seen as an improvement to a Virtual machine. Each Virtual Machine in a server needs a separate Guest operating system to function. All the Docker Containers in a server use the same underlying Operating System of the server, hence Dockers are lightweight when compared to Virtual Machines. Also, Dockers are faster to spin up and execute when compared to Virtual Machines.

The Docker platform contains the following components

Wednesday, August 26, 2020

What's new in Angular 10

Angular 10 was released on June 24, 2020. Angular 10 offers support for TypeScript v3.9

To upgrade an existing Angular 9 application to Angular 10, just run the ng update command as follows

What's new in Angular 9

Angular 9 was released on February 6, 2020. Ivy compiler and runtime are now made default in Version 9, this helps in faster build and smaller bundle size. Angular 9 has been updated to work with TypeScript 3.6 and 3.7
To upgrade an existing Angular 8 application to Angular 9, just run the ng update command as follows

ng update @angular/cli @angular/core

One of the major features of Angular 9 is making the Ivy compiler as default, this offers the following improvements

What's new in Angular 8

Angular 8 was released on May 28, 2019. Angular 8 provides features like Differential loading, Dynamic imports for lazy routes, Web workers, TypeScript 3.4 support and Angular Ivy & Bazel as an opt-in preview features.

Differential loading
With differential loading, the Angular production build will produce 2 separate bundle files. One ES5 bundle for legacy browsers. Another ES6 bundle for the latest browsers which support ES6 features. This helps in improving the loading speed and performance in modern browsers since this bundle file is smaller in size.

Tuesday, August 25, 2020

Angular Elements

Angular EventEmitter

Using EventEmitter with @Output

In the previous post, we saw what EventEmitters are and how they are used in combination with @Output decorator to handle communicate from Child component to the Parent component. In this post, we shall see a full example of how this is implemented.

In the example, we have a ParentComponent and a ChildComponent, the child component has a button and a @Output decorator. In the buttons click event, we will trigger the emit event of the EventEmitter associated with the @Output parameter, we will also send a payload along with the emit.

What are EventEmitters?

Angular applications are made using Components, most often we will have to arrange the components in a hierarchy (parent/child components). We will have to pass values from the parent to child components and from the child to parent component to make the App functional.

To pass values from a parent component to a child component we use the @Input property/decorator.
To pass values from a child component to a parent component we need to emit an event using @Output and EventEmitter. Both are parts of the @angular/core.

Sunday, August 23, 2020

Angular Observable

Promises vs Observable

Promise is eager, once they are initialized they trigger the underlying actions and returns the result
Observable is lazy, they don’t trigger until it has a subscriber.

Promises returns only one value
Observable can return multiple values overtime to its subscribers

Promise cannot be canceled, once a promise action is triggered it will execute and return the result
Observable can be canceled, we can call unsubscribe to stop receiving responses from the observable

Promises can be converted to observables, the RxJs library provides a from operator which can convert a promise to an observable. We can use this to deal with some legacy code that is returning promises.

import { from } from 'rxjs';
const myObservable = from(myPromise)

Consuming Observables using async pipe

To consume an Observable using async pipe we need to use the | async syntax in the components view template. In the previous post, we saw how to consume an Observable (response from a http API call) by subscribing to the Observable.

The view template consumes this Observable and displays the response from the http call in the View template. The async pipe automatically subscribes and unsubscribes to the Observable, whenever a new value is emitted from the Observer the async pipe automatically detects the change and refreshes the component.

Consuming Observable using Subscribe

To consume an observable by subscribing, we need to call the subscribe() method and capture the result/error objects returned by the observable. In this sample, we will get a list of users using a http.get call which returns an observable.

Creating observable using Inline Arrow functions

In the previous post we created a separate function and passed it as a parameter to create an Observable. In this post we shall see on how to create an Observable using an inline arrow function.
In the below example we will create an Observable with an inline function which emits the current time, we use setInterval to emit a new value every 1 second.

Creating Observable

We can create our own Observable by creating a function that takes an observer parameter. The function will be passed to create the Observable. When someone subscribes to the observable, the function is called and returns the values emitted from the function.

In the below sample we create a function listGenerator, which takes an observer as a parameter and emit list values one at a time using .next().

Friday, August 21, 2020

What is Async Pipe?

Async Pipe is an impure pipe which helps to make it easier to work with Observables. The Async Pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

For promises, it automatically calls the "then" method.
For observables, it automatically calls subscribe and unsubscribe.

To use the Async Pipe to handle observables in Angular template we use | async followed by the observable, this will automatically subscribe to the observable and refreshes the component whenever a new value is emitted from the observable.

AsyncPipe uses the OnPush change detection out of the box. We need to make sure that all our business logic is immutable and always returns new objects.

Observable in Angular

Angular internally uses Observables for different features, which needs to listen to specific sources and trigger actions based on specific events/values. Angular uses Observables for the following.

What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. RxJS provides an implementation of the Observable type.

RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on.

What is an Observable?

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes.  Observables get their name from the Observer design pattern. The Observable sends notifications while the Observer receives them.

Saturday, August 15, 2020

Angular Services

Angular Dependency Injection

Dependency Injection (DI) is a pattern in which a class gets its dependent classes from an external source/framework instead of instantiating them within the class.  Dependency Injection makes an application easy to maintain and makes testing easier, since the dependent objects are injected from outside we can use Mock objects to test the behavior of a class when the actual object is not ready for testing.

Angular Singleton Services

A Singleton Service is one which has only one instance shared across the entire Angular App, it is a great way to share data across different components even if they don’t have any Hierarchal relationship. Services can be declared Singleton by setting the providedIn property of the @Injectable() to "root", when creating the service.

@Injectable({
  providedIn: 'root',
})

Friday, August 14, 2020

Redux Overview

Redux Thunk Overview

Fetch async data using Redux Thunk example

In the previous post we saw about setting up Redux Thunk for a React Redux application, in this post we shall see an example for fetching async data from an API call using axios and redux thunk, and update the store with the response from the API call.

Assuming that we have the required npm packages installed and the redux-thunk middleware configuration is setup as specified in the previous post we will go ahead with the actual implementation of redux-thunk and axios api calls.

We create 2 actions, first to set the locations array in the store and the 2nd to set a success/failure message.

Adding Redux Thunk Middleware to a React-Redux App

In the previous post we saw about Redux Thunk middleware and its need, in this post we shall see on how to setup the redux-thunk middleware in a React Redux application. Assuming that we have a working React Redux application we shall see on how to add redux-thunk middleware to it.

To start with we need to install the redux-thunk middleware npm package.

npm install --save redux-thunk

Next we need to add the middleware in the createStore method as follows.

What is Redux Thunk

Redux Thunk is a middleware that lets us perform asynchronous operations like API/Ajax calls before modifying the data in a store. Middleware provides a way to interact with actions that have been dispatched to the store before they reach the store's reducer. Examples of different uses for middleware include logging actions, reporting errors, making asynchronous requests, and dispatching new actions.

Adding Redux to a React App

In the previous few posts we saw about Action, Reducer and Store concepts about Redux. In this post we shall see on how to put all of these together to add a Redux store to a React application.

In this sample we will create a simple React application, with a textbox where the user can type his name and a button on click of which a Welcome message is displayed with the name. The onChange event of the textbox and the onClick event of the button will dispatch actions to update the corresponding property in redux store.

mapDispatchToProps in Redux

mapDispatchToProps function is used to dispatch actions to the store in a react-redux application.
To dispatch an action to the store we need to call store.dispatch. In a React Redux application the React component does not have access to the store directly hence it cannot call store.dispatch. The connect method which connects react and redux provides the mapDispatchToProps through which react components can dispatch actions.

If mapDispatchToProps is not defined in connect, there is another way to dispatch actions from React components. In this case props.dispatch is passed to the component and using this we can dispatch actions to the store.

mapStateToProps in Redux

The is a function which takes the state as an input parameter and maps the properties in the state to props mapStateToProps  in the component.

mapStateToProps take the state object (the same value returned by a call to store.getState()) as the first argument and return a plain object containing the data that the connected component needs.  This function should be passed as the first argument to connect, and will be called every time when the Redux store state changes.

store in Redux

In Redux store is the state object which holds the Application state. The current state can be accessed using store.getState() and any changes to the state can be performed by dispatching an action to the reducer.

In the previous posts, we saw how to create the store object using createStore and use it to initialize the application. Redux store also allows us to subscribe to events that update the store object. This can be useful to debug changes to the redux store.

In the createStore code of the previous example we will add a subscription to display changes to the state to the console as follows.

combineReducers in Redux

In the previous post, we saw about Redux reducers, how to create them, and bind it to the store when the Application gets initialized. This approach of creating and initializing a single reducer works well for small Applications.

When the application grows it might be difficult to hold the state of all the components in a single file, as it will grow too big making it difficult to maintain, we would like to split the reducer code across different reducer files for maintainability. To achieve this redux provides a utility combineReducers(), this can take multiple reducers and merge them into a single reducer before assigning it to the store.

Let us extend the previous example, add multiple reducers and use combineReducers() to merge them into a single reducer and assign it to the state as follows.

Reducers in Redux

Reducers are pure functions in redux which are used to modify the state object of the Application. All Actions are handled in reducers they will get the payload from the action and modify the state as defined.

Reducers take the previous state of the app and return a new state based on the action passed to it.
As pure functions, they do not change the data in the object passed to them or perform any side effect in the application. Given the same object, they should always produce the same result. Actions performed on the state always return a new state. Thus, the state is very easy and predictable.

In the previous post, we was a SET_NAME action below is the reducer which handles the SET_NAME action.

Actions in Redux

An Action is a plain JavaScript object which has a Type property which defined the type of the actions and an optional payload. Actions are triggers which are used to send information from the application to the store and these are the only way in which the redux store can be modified.

Below is an example of a simple action object.

What is Redux?

Redux is a predictable state container for JavaScript applications.

For React applications Redux provides a centralized state container for the whole Application. Redux holds a large JavaScript state object which can be shared across the application.

Thursday, August 13, 2020

React TypeScript Examples

React TypeScript stateless Function component example

In the previous post, we saw on how to create a React component with state and event handlers using TypeScript. We can also create simple function components using TypeScript which does not require a state. Usually, these types of components are used for UI components. Class components with the state are used for container components and Function components are used for UI only components which do not interact with the state containers.

In this post, we will see how to create a simple Hello World function component in React using TypeScript.

React TypeScript Parent - Child components example

In the previous post we saw a React class component written in TypeScript, the component had state support and event handling (button click event and text change event). The component has a textbox and a button, we handle the onChange event of the textbox set the value in the name state property. We capture the onClick event of the button and set a greeting text in the message state object, this message is displayed in the screen

In this post we will alter this component a bit so that the greeting message is passed as a property from the parent component.

React TypeScript component with State and Events

In the previous post we saw on how to do a simple Hello World application in React with TypeScript using the create-react-app package. In this post we will move on the next step we will add state support and event handling (button click event and text change event) to the component.

The React component initializes state, notice that we are using the State interface with strongly types properties to define the state object, this is the advantage of TypeScript it allows us to define strongly typed properties which help us capture type errors during development. The state object has 2 properties message and name.

React ref overview

React Component Lifecycle methods examples

React Component Lifecycle Overview

React ES6 Examples

React 16.3 Context, Ref & Lifecycle changes

React 16 Fragments, Portals & Error boundaries

React Overview

Angular Provider Scope

In the previous post, we saw on how to make a service available globally by declaring the @Injectable providedIn: 'root'. We can also declare module-level services using ProvidedIn, in this post we shall see on how to declare module-level service using @Injectable

To limit the scope of a service to a module we need to specify the module in the providedIn instead of ‘root’. In the below code the HellpService is made available only to the HelloModule, the service is not available to any other Modules in the Application.

Angular Service Scope

In Angular, Services are a great way to share information among Components that don't know each other. Based on how we register a service we can control the scope/visibility of the service across the Application.

Services can be registered with 3 levels of scope
1. Global Scope
2. Module Scope
3. Component Scope

Wednesday, August 12, 2020

What are Angular Services?

 In Angular, a Service is a class that is used to provide shared features across different components. Components are the View layer they deal only with UI specific features. Functional tasks like ajax calls, business logic, validations, logging, etc are delegated to the services.

Services are a great way to share information among Components that don't know each other. Based on how we register a service we can control the scope / visibility of the service across the Application. Services can be registered with 3 levels of scope

1. Global Scope
2. Module Scope
3. Component Scope

Sunday, May 24, 2020

React TypeScript Environment Setup

HelloWorld create-react-app Application using TypeScript

In the previous post we saw on how to setup a React Application using TypeScript and webpack, in that post we manually installed the required npm packages, created the config files and the React component files from scratch, this was a good way to know how React application builds and executes, but it takes time to do this setup.

In this post we will use the create-react-app package from Facebook to quickly create a React application using TypeScript.

Open a command prompt and run the following command.

HelloWorld example in React with TypeScript

In the previous post we did setup the Development environment to develop React applications using TypeScript. In this post we will use this environment and create a Hello World React application using TypeScript.

Assuming we have a root folder and the environment setup with required npm packages installed and config files we will go ahead and create the Application files. First let us create the following folder structure for the React components.

Set up React dev Environment using Webpack and TypeScript

In the previous posts we saw on how to create React Applications using JavaScript and JSX. We can also write react applications using TypeScript. The build environment setup will be different when we use TypeScript.

When we created React Applications using JavaScript (ES6) we used the Bable loaders to transpile ES6 code into browser compatible JavaScript code, in case of TypeScript we will have to use a TypeScript loader (ts-loader) instead of Bable.  In this post we shall see in details on how to setup the environment for creating React applications using TypeScript.

First to start with let us create a new project by running npm init

React Boilerplates Overview

React Hello World using create-react-app

In this post we shall see on how to install the create-react-app boilerplate and how to create a simple Hello World application using the boilerplate.

Let us create a React application hello-world using the following command.

npx create-react-app hello-world

The command will install all the required packages and the basic files for a startup React application. Once the command is completed it creates the following files and folders.

What are React Boilerplates

In the post Setting up React Environment, we saw the process to setup the environment to do a simple Hello World application in React, we know that it takes quite a bit of time and effort to get started with a simple Hello World application.

We need to install react, bable and web-pack packages. Create configuration files for web-pack and bable. Create a root Html page (index.html), create at least one React component and a root class to load the component in the HTML DOM using ReactDOM.render. That’s quite a bit of work to do the simplest Hello World sample.

Friday, May 22, 2020

React Environment Setup and Build Tools Overview

Source Map

Source Map helps us debug JavaScript code in production. Source Map creates a mapping between the original development version of the JavaScript / JSX files and the compiled and bundles production version of the JavaScript files, thereby allowing us to debug in production.

In the previous posts we saw how Bable compiles the ES6 & JSX code and transforms them into JavaScript and how webpack bundles the individual files into a common bundle.js file. As a result of the transpilation, minification and bundling process we are left with a large JavaScript file which is almost impossible to debug, but we cannot avoid these steps since they are required to make the JavaScript application secure and performance efficient in the production environment. If so then how do we debug issues in production environment, the answer to this is Source Map.

Thursday, May 21, 2020

Bable

Babel is a JavaScript compiler which is used to transform ES6 JavaScript code to ES5 JavaScript which the browsers can understand. This transformation is called transpilation. React components are generally written using ES6 classes and JSX syntax, bable loaders are used to transpile ES6 and JSX code to core ES5 JavaScript.

Webpack cannot compile ES6 JavaScript code, hence it used loaders to transpile ES6 and JSX code. In the React sample we used bable-loader in the webpack configuration to compile ES6 and JSX code into native JavaScript code.

For the React Application we used the following 3 bable packages

npm package-lock.json

The package-lock.json is a new file introduces in npm v 5.*. The goal of introducing this new file is to resolve issue due to installing different versions of packages.

In the previous post we saw about the semantic versioning for npm and the various wild cards associated with this versioning. We saw that the package.json by default uses the carot (^) wildcard for package versioning, this allows for auto upgrade of the minor and patch versions.

Let us say we have the following entry in our package.json file for react
"react": "^16.8.3"

Wednesday, May 20, 2020

npm semantic versioning

NPM uses Semantic package versioning, which is a 3 part versioning like 7.5.5
<Major version>.<Minor version>.<Patch version>

Patch version – Patch versions will includes bug fixes
Minor version – Minor versions will include feature additions without breaking changes
Major version – Major version changes can include breaking changes

NPM

NPM is the package manager for Node.js, NPM is also used to install dependent packages for client side applications like React, Angular etc. NPM takes care of installing and maintaining the dependent packages for a project.

The command npm init is used to create a new project, this command will create a project.json file which will record all the dependent packages required for the project. If also records the commands to be executed when we build/run/test the Project.

The package.json file for our Hello World React application looks as follows.

Webpack

Webpack is a module bundler, its main purpose is to bundle all the dependent files into a single .js file which helps optimize the page load. Apart from bundling webpack can also be used as a task runner by configuring a sequence of tasks in the build process like cleanup target folder, bundle files, copy files etc. Webpack by itself is a big topic, in this post we shall see the minimal configuration required in webpack to bundle and load a React Application.

Webpack is configuration driver, remember we created a file in the webpack.config.js previous Hello World post, this is the webpack configuration file. The most minimal webpack configuration includes and entry (input) and an output.

Sunday, May 17, 2020

React Setup and Build Tools

In the previous post we saw how to setup the environment to develop a Hello World React App, we saw that we used a set of npm packages and tools like webpack, bable etc to setup the environment, in this post we shall see the purpose of each of the tools in setting up the React Environment.

Setting up React dev Environment using Webpack and babel

Modern web development frameworks like Angular / React are complex and involves complex environment setup before we could write our Hello World program. Setting up the development environment for React is a tedious task. In this post we will try to set up the development environment and display Hello World using a react component.

1. First let us create a folder ReactHelloWorld, we will setup the environment and create the Hello World component in this folder.

2. Next make sure node is installed in the pc, if not installed already install the latest version of Node.js. We can check if Node is installed by running the command node –v, if Node is installed this command will return the version of Node.js Installed in the pc.

ReactHelloWorld>node –v
v8.12.0

Saturday, May 16, 2020

React Fiber Overview

What is Reconciliation?

A React application comprises of various React components, the components are organized in a tree structure with a root component and other child / nested components. When the React application loads it creates the component tree in memory called the Virtual DOM. Whenever a component gets updated in the tree React runs an algorithm to determine what changes should be made to the DOM to reflect the changes in the UI, this process of comparing the changes to update the DOM is called Reconciliation.

React reconciliation is based on 2 assumptions

What is React Fiber

React Fiber is a re-write of React’s core algorithm which aims in improved rendering and responsiveness of the UI. React Fiber helps in improving performance of UI intensive operations like animation, layouts etc. React Fiber improves the algorithm to render / re-render changes to the DOM thereby improving the performance / UI responsiveness of React applications.

To better understand React Fiber we should first understand the concept of Virtual DOM and Reconciliation in React, let us look at these in brief.

Wednesday, May 13, 2020

React 16.9 Profiler Overview

React.Profiler component example

In the previous post we saw in detail about the React.Profile component and how it is used to capture performance metrics of a React Component. In this post we shall see a small example on how to use the React.Profile component to measure and display performance metrics.

We will use the useEffect example and add React.Profile to it. The sample consists of a Parent component App, child component UseEffectComponent and the Root ReactDOM to load the App component. We will add Profiler to the App component in the Root and add Profiler component for UseEffectComponent in the parent App component as follows. Remember we are using create-react-app boilerplate to create these examples which will have additional supporting files.

React.Profiler component in React 16.9

Profiling React applications for performance was introduced in React 16.5 using a React Profiler DevTools plugin, this works but not straightforward. To get this working we need to open the developer tools, record the performance metrics and later analyze the results. Also it records the performance of all running React Apps.

React 16.9 introduces the new React.Profiler component which avoids the drawbacks of the earlier DevTools based Profiler. The Profiler API is programmable and we can configure it only for specific applications. Also the Profiler API does not need DevTools support it can capture and write performance logs to the console directly.

Friday, May 8, 2020

React 16.8 Hooks

useEffect Hook example in React 16.8

In the previous post we saw an example of how to use the useState hook in a function component to maintain and update state props. In this post we will see an example on how to use the useEffect hook to perform side effects from a function component.

In this sample, we will use the useEffect hook to change the title of the document. We will use the value from the state prop title to set the document title as Hello + {title}. Initially the title will be displayed as Hello React, on clicking a button we change the state value of title, which in-turn triggers the useEffect and changes the document title.

useState Hook example in React 16.8

In the previous post we saw that the useState Hook is used to define state props in a function component, in this post we shall see a small example on how the useState hook works in action.

In this post we will create a function component and define a state prop count using the useState hook, we will attach a function setCount which will be used to change the value of the count prop. We will also attach the setCount function to the click event handler of a button, so that each time the button is clicked the setCount function will be called which will increase the value of the count state prop by 1.

Hooks in React 16.8

Hooks were introduces in React 16.8, hooks let us create function components in React with state and other React features. Usually for a React component to have state it should be created as a class component.

React 16.8 introduces the following basic hooks

Thursday, May 7, 2020

React 16.8 Lazy, Memo and contextType

Lazy loading React components

Lazy loading is loading dependent modules / components dynamically, this is done to optimize the initial load time of larger React Applications which have multiple components and 3rd part library dependencies.

In React 16.6 lazy loading is enabled by using React.lazy function and the Suspense component. React.lazy is used to lazy load react components from the same or different bundle file and the Suspense component is used to display a fallback UI till the dependent component / bundle is loaded. Lazy loading and code-splitting works together to enable optimization of initial load time for large React Applications.

What is Code-Splitting?

Code-spitting is a feature supported by bundling tools like web-pack to split the React Application bundle into multiple bundle files to improve the performance. To understand bundles this we should first go to the basics of how React applications are bundled and rendered to the browser.

In the React Environment we see how the React components are compiled and bundled before being rendered to the browser. We use Bable to compile the react Application and web-pack to bundle the compiled JavaScript into a bundle.js file.

Wednesday, May 6, 2020

React.lazy with Suspense example

In the previous post we saw that React.lazy is used to lazy load react components from the same or different bundle file and the Suspense component is used to display a fallback UI till the dependent component / bundle is loaded.

In this post we shall see a simple example which uses React.lazy to lazy load a Child Component and display Loading… text till the child component is loaded. The example has 2 components, the App component is the parent component which laze loads the ChildComponent.

React.memo example

React.memo was introduced in React 16.6 to create performance efficient function components, these components are similar to PureComponents except that they are function based. These components will re-render only when the props of the component changes and not when the parent component re-renders, thereby reducing the number of render cycles and improves the component performance.

In the below example we will create a React.memo component MyMemoComponent which will take a prop msg from the parent and display it. Remember that the memo component will only re-render when the props passed to it changes.

React.memo & React.lazy in React 16.6

React 16.6 introduces 2 main features React.memo and React.lazy

React.memo
is similar to PureComponent, it only re-renders if its props are changed. They both offer performance booster to the component by reducing the number of renders. The difference is that PureComponent works with classes and React.memo works with functions.

Tuesday, May 5, 2020

React 16.4 Pointer Events

React 16.4 Pointer Events example

Pointer events were introduces in React 16.4 to handle mouse and touch events. In jQuery we have only mouse events, now with the introduction of touch screen and devices like iPad we need to handle touch events also. React now introduces pointer events which can handle both mouse and touch events.

In the below example we will capture 2 Pointer events onPointerEnter & onPointerLeave. We will add these events to a DIV, when we move the mouse over the DIV or touch the DIV the onPointerEnter event will trigger in the event handlers we toggle the isHover state property which will in turn change the color of the DIV. By default the DIV gets silver color, when we hover the mouse over the DIV or touch the DIV its color will change to golden color.

What's new in React 16.4

React 16.4 consists of mainly 2 things. First is the introduction of Pointer Events, and second is a fix to the getDerivedStateFromProps component life cycle event.

Pointer events are used to handle mouse and touch activity like hover, enter, leave etc. They are similar to jQuery mouse event handlers like mouseenter, mouseleave, mouseover etc
. The difference between jQuery mouse events and React pointer events is that the Pointer events support both Mouse events and Touch events.

The following are the pointer events supported in React 16.4