Introducing GatsbyJS

Overview

There is a new modern web development architecture in town called the JAMstack. It is based on client-side JavaScript, reusable APIs, and prebuilt markup. GatsbyJS embraces this philosophy by creating blazing-fast and secure apps and sites using modern technologies like React and GraphQL. In this article, we are going to build a complete modern static blog site with Gatsby using React components and GraphQL and a methodology in line with the JAMstack, all thanks to the power of GatsbyJS. We will be using GatsbyJS version 2 to build a fast static blog that you can host very cheaply, even for free if you wish, all with unprecedented speed and very secure in nature. Static sites also have the added advantage of being great with regards to search engine optimization (SEO), so that is also a plus. Some of the major topics that will be covered include how to get started creating static sites with GatsbyJS; creating reusable React components like headers, buttons, and footers; working with Gatsby’s plugins and extensibility points; using GraphQL to query for data; and deploying a static site to a modern web hosting provider. This article assumes you are familiar with basic JavaScript, HTML, CSS concepts, basic knowledge of the command-line interface and running basic commands.

The JAMstack Architecture

Before we start to learn about GatsbyJS, I think it’s important to understand about this new concept called the JAMstack. What is JAMstack? JAM stands for JavaScript, API, and Markup. The term was coined by Mathias Biilmann, cofounder of Netlify . As per the definition on the official JAMstack website, JAMstack is a modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup. In other words, a site that adheres to JAMstack only uses static content like HTML, images, CSS, JavaScript, and calls external APIs over HTTP that typically exist in the form of REST endpoints. These APIs can be created by you or by an external organization that provides a particular service. The client logic lives in the static JavaScript files, and the business logic comes from these external endpoints. In more traditional applications, the rendering of a site happens on the server at runtime, while in a static site, the rendering happens at build time in your computer while building the application or in a build server if you wish to do so.

So what are the advantages of using the JAMstack? For starters, JAMstack offers better performance compared to server-side rendered applications, especially if you host your static site in a CDN, you can get subsecond access times in this way. Static sites offer better security because they offer a reduced attack surface compared to dynamic sites. Removing system components, like a database from the equation, can have significant advantages, including eliminating SQL injection attacks. Moving he business logic away from your app also decreases the risk of an attack. Now it’s the responsibility of API creators to secure that part of the application. Static sites are cheap to host and scale. You can serve your site in more places faster. Finally, if your goal is good SEO performance, static sites can also dramatically improve the discoverability of your site.

So to recap, when is a site built with JAMstack in mind? A site is built with JAMstack in mind when all site components are static; you create site assets like HTML pages at build time instead of runtime; when it uses JavaScript to add dynamic programming on the client side, it could be any front-end framework like Angular, Vue, or React, for example, or a library such as jQuery or even plain old vanilla JavaScript; uses markup that is HTML, but also CSS, images, or any other type of static content; and finally, it calls external APIs that perform the heavy lifting when business logic functionality or database access is required.

Now let’s see when a site does not adhere to JAMstack. If you build a site with a server-side render framework like a content management system (CMS), such as WordPress, for instance, your site does not adhere to the JAMstack framework. The same applies to a web-application created with more established frameworks like C#, and .NET, Java, and Spring, and Node, and Express just to name a few. These frameworks render your application in the server, hence not adhering to JAMstack either. A less intuitive example is a single-page application created with a front-end framework like Angular, Vue, or React that is isomorphic in nature that is a sort of a blended server-side rendered application and a single-page application.

So what does Gatsby and JAMstack have in common then? Well, Gatsby adheres to all tenants in the JAMstack, and does it magnificently using the best technologies and workflows that work in tandem to provide a great user experience for developers. Now that we have a clear understanding of JAMstack and its advantages, it’s time to explore Gatsby in more detail. We will do that next.

What is GatsbyJS?

GatsbyJS is a modern front-end framework for creating static sites and applications. It’s been built upon modern technologies such as React, GraphQL, and Webpack, amongst other front-end technologies. One thing that makes Gatsby unique is that you  don’t have to know React or GraphQL to start working with Gatsby. You can learn Gatsby as a way to introduce yourself to the world of React, GraphQL, and modern front-end development in general. Its creators have taken out the guesswork of configuring a modern workflow to build sites based on these technologies; therefore, creating sites with Gatsby is fun, productive, and easy, and the results are great. I mentioned React and GraphQL, but what are these and what do they do?

React is a JavaScript library for building modern user interfaces. It was created by Facebook to help their development teams in creating modern and responsive applications. Along with Vue and Angular, it’s the defacto framework to build modern apps today. With React, the focus is on building small components that you can reuse throughout the application.

GraphQL is also a technology created by Facebook and is a query language that allows you to query for data in a declarative way by describing the data you intend to get from a data source. It lets you specify the data your application needs and gets that data in the format you initially requested. We will be using GraphQL for querying data when building blog site.

The goal of Gatsby is to create static sites and applications comprised of HTML, CSS, JavaScript, and other static content. The difference between Gatsby and other static site generators is the way Gatsby accomplishes this goal. Think about the different types of data. It could be Markdown files, an external database, or an API, a JSON file, or even a text file. Gatsby lets you query with this data with GraphQL in the format you need. For example, you can query data from a Markdown file sitting in your local drive that you intend to use as the content for our blog post. GraphQL grabs the file content, its file name, the blog post title, and the creation date and uses this information to create a static HTML file ready to be uploaded on the server.

Okay, another example. Let’s say you want to create a page with a list of popular products that your company sells. This data changes once every three months or so and resides in a database. The traditional approach was to create a server-side rendered application that connects to a database, generally, through a endpoint exposing this data and then generate the page on the fly at runtime with the desired information. With Gatsby, we take a different approach. We call the endpoint with GraphQL, fetch the data you need, and then create a static HTML page with the required data. The information is only queried once and served from the server as a prebuilt static HTML file. Another cool thing about Gatsby is its rich plugin ecosystem which brings a lot of functionality to Gatsby.

Alright, we went over React, GraphQL, and the merits and benefits of static sites and using Gatsby. Gatsby is the way to go when you want to build a site that is fun to develop, uses a modern workflow and future-proof technologies, adheres to the tenants of JAMstack, is fast, secure, inexpensive to host, and has excellent SEO capabilities.

Gatsby goes beyond creating static sites. React and GraphQL are used by thousands of companies and developers to create sophisticated web applications. Since Gatsby uses React, we can use Gatsby to develop sophisticated web applications as well.

Lastly, I want to go over browser support for Gatsby briefly. Gatsby currently supports the same browsers as the current stable version of React, that is Internet Explorer 9 and above, as well as the most recent versions of other popular browsers. They are also known as ever-green browsers, in other words, browsers that self-update. Next, let’s go over the installation process of GatsbyJS.

What is the Web Animations API?

In the context of web apps, animation is nothing more than the visualization of change over a specified duration. This visualization of change is very important because when done right we can use this to dramatically increase the user experience of an app and make our apps feel more refined and well designed.

At the highest level, the Web Animations API is a standardized JavaScript API which is baked into browsers that allows developers to animate DOM elements. CSS was always been the most performant way to animate on the web because the CSS animations engine can run animations on the GPU instead of the CPU allowing us to achieve smooth 60 fps animations. The Web Animations API finally allows us to write animation logic using JavaScript and opens up the browsers animation engine allowing us to run these animations on the GPU. As well as performant animations there are host of other benefits the Web Animations API provides us. Because it is a JavaScript API we can easily create dynamic animations by altering durations, easing methods and other variables; something which is very hard to do in CSS. The API provides very flexible playback control which allows us to Pause, Rewind, Skip and even change the rate of playback and more. The API is Promise based so it is really easy to chain multiple animations or run other logic when the animation completes. And because the Web Animations API is a browser feature there are no external dependencies to manage or maintain. Today most JavaScript libraries take a component based approach. Whether that’s using Angular, React, VueJS or just native web components the Web Animations API fits in with this architecture because the JavaScript used to create this animations can be embedded into the components easily without any dependencies. These are great benefits provided by the Web Animations API which we can use to harness the power of the GPU to create silky smooth animations that are dynamic and flexible.

Learning the Angular CLI

Exploring the Angular Command Line Interface (CLI)

Installing the CLI

sudo npm install -g @angular/cli
ng --version

Using the CLI

ng --help
ng build --help

Creating New Angular Projects

The ng new command

ng new app-name

New project generation options

ng new --help
ng new app-name --routing
ng new app-name --style=scss --routing --dry-run
ng new app-name --style=scss --routing --prefix=vsrao

Serving Angular Applications for Development

The ng serve command

ng serve --help
ng serve
ng serve --open

Customizing the development server

ng serve --port=8000 --open
ng serve --host=whatever.dev.company.com --open

Generating Angular Application Code

Creating new code with blueprints

With the Angular CLI you can generate the different entities used to build your application. You will be able to easily generate Components, Directives, Services, Pipes, Models and Interfaces, Route Guards and Modules. When generating a blueprint, your command will follow the following template:

ng generate [schematic] [name] [options...]
ng generate --help

Available schematics: application, class, component, directive, enum, guard, interface, module, pipe, service, universal and appShell.

Generating components and modules

ng generate component contact-list --dry-run
ng g c contact-list --dry-run
ng g c contact-list --dry-run --flat
ng g c contact-list
ng generate module shared
ng generate component shared/avatar --module=shared

Generating directives

ng generate directive shared/directives/non-numeric --module=shared

Generating services

ng generate service services/api
ng generate service services/api --module=app

Generating pipes

ng generate pipe pipes/phone

Generating models

ng generate class models/contact

Generating interfaces and enums

ng generate interface models/contact
ng generate enum models/contact-type

Generating route guards

ng generate guard auth

Building Angular Applications

A build pipeline for an Angular app

There are many steps involved in building an Angular application. Since Angular applications are written in TypeScript and ES6 and beyond, the build pipeline is quite involved. We need to Transpile TypeScript and ES6+ code, bundle our application into one file, or split across many, minify files by removing newlines and white space, mangle our application bundles to make files even smaller, and also generating source maps. Aside from that, we also need to deal with CSS and other assets, such as compiling from Sass to CSS, possibly inlining CSS, having scoped styles, and copying or inlining images. As you can see the process is very involved, but the Angular CLI takes care of all this for us using Webpack under the hood, all with a simple command, ng build. The ng build command also comes with several options.

Configuring different build options

By default, the ng build command runs a development build due to which the JavaScript bundles are not optimized meaning they are neither minified nor uglified for performance. Also the bundle names do not contain a hash for cache busting.
A production build can be run using ng build --prod. For generating source maps in a production build we need to use the ng build --prod --sourcemap command. Lastly, if you wish to analyze the generated bundle files, using a tool such as webpack bundle analyzer use the ng build --prod --stats-json command. Running this command will generate a stats.json file, which you can then upload on webpack.github.io/analyse/ . On this site, you can analyze the different bundles that the build pack run generated for you. You can analyze chunks, the assets, and see the size of each of them.

Setting up build scripts

In the package.json file, we can setup the below npm scripts:
"build:dev":"ng build --stats-json"
"build:prod": "ng build --prod --stats-json"
Setting up npm scripts will make automation much easier.

Running Tests

Built-in test runners and scaffolding

When you create an Angular application using the CLI, a testing pipeline is already set up for you. To run your unit tests, a karma configuration file, karma.conf.js is generated. Karma is used as a test runner using jasmine as a testing framework, and is set up, by default, to run your tests in Chrome. Additional setup can be seen in test.ts. Essentially, this provides additional setup to initialize the Angular testing environment. You can write your tests in TypeScript and the CLI will take care of transpiling that for you.

The ng test command

In order to run your unit tests, you use the ng test command. This will take all of your spec files, transpile them in memory, and run your unit test in Chrome.

Test run options

Running the ng test command runs the test in watch mode. However, if you prefer not to do that, you can use a single run flag. By running the ng test --single-run command the test will only run once and then exit. This will be needed in a Continuous Integration environment.
You can also generate code coverage reports when running your tests. To do so, you need to use the code coverage flag. Running ng test --single-run --code-coverage command will not only run your tests but will also generate code coverage reports using Istanbul. Once it is complete, it will create a new coverage folder, with an index.html page for your report.

Ejecting from the Angular CLI

The tooling provided by the Angular CLI is quite extensive. It can generate applications, application code, and also set up build and testing pipe lines for you. However, it is not uncommon for a development team to ask specific needs over the build process, in order to have finer control. It is for these purposes that the Angular team created an eject feature. You can use this feature if you feel that you want to manually take care of running and building your application. To do so, you can use the ng eject command.

Conclusion

The Angular CLI is truly a great tool that will allow you to be productive building Angular applications. I recommend subscribing to notifications on this GitHub repository – https://github.com/angular/angular-cli/, as it will allow you to keep up to date with new features and be notified of new releases. The Angular team have some great things planned for the CLI. I also recommend subscribing to the official Angular Blog – https://blog.angular.io/ for keeping up to date.

What’s New in React 16

Introduction

Facebook recently announced the release of React 16, a complete rewrite of the React library. The new core architecture, code-named Fiber, keeps most of the API intact and backward compatible, so you can update existing apps without running into issues. Fiber introduces lots of new highly anticipated features and improvements to React. This blog post is about what’s new in React 16. It will cover the new features that lets React developers catch and handle JavaScript errors in React components; render elements into different locations in the DOM outside of the main component tree using portals; return multiple elements without having to wrap them in a parent element using new render return types like arrays, strings and numbers; also return null from setState to prevent unnecessary state updates and re-renders and more.

You can start using React 16 today. When you install React in a project or create a new app using the create-react-app tool, it will automatically install the latest version of React and ReactDOM. As mentioned above, React 16 is backwards compatible. So if you are currently running your app on a previous version of React without any console errors or deprecation warnings, updating to React 16 will not break your app. It should be a seamless transition. Now with a complete rewrite of the React Library comes a few minor breaking changes that only affect uncommon use cases. You can view all the breaking changes. A welcome change is that React is now available under the MIT license. The uncertainties created by Facebook’s previous BSD+Patent’s open source license was a concern to many developers, startups and companies using React. So now React licensing is more flexible. You can use React in your project without having to worry about the previous patent’s clause. Now if you are not able to upgrade immediately to version 16, React 15.6.2, was also published under MIT. Also note, the React 16 update does not mean that whatever you have learned so far about React is immediately obsolete. The API itself hasn’t changed, and most of the skills you have learned are still important, fundamental skills you will continue to use. So if you are eager to learn about everything that is new in React 16 next I will cover the new component life cycle method and error handling feature that lets us catch and manage errors when rendering React components.

Take Control of Errors with componentDidCatch()

One of the biggest changes in React 16 is how React handles JavaScript errors. Normally, a JavaScript error inside a component, for example, like an uncaught type error will break the entire app. A JavaScript error in a part of the UI shouldn’t break the whole app. So in React 16 error handling was improved to avoid these types of situations where runtime errors during rendering breaks your app. It provides a built-in solution for handling errors gracefully with a new life cycle method called componentDidCatch(). This life cycle hook gets triggered whenever a childs component render or life cycle methods throw an error. When an error occurs, componentDidCatch() catches the error and instead of crashing the entire app, the app continues to run as normal displaying all the UI except for the faulty component. You can even display a fallback UI to replace the component that crashed.

Catching Errors with Error Boundaries

With the componentDidCatch() lifecycle method comes a new concept of an error boundary. Error boundaries are wrapper components that use componentDidCatch() to capture errors anywhere in their child component tree and display a fallback UI in its place. They provide an easier way to keep the error catching and conditional rendering logic reusable and maintainable in your app. You create an error boundary as a class component. Any errors caught in the component tree get reported up to the Error Boundary’s componentDidCatch() method thereby providing a handy way of sending error reports to an error tracking or monitoring service. The componentDidCatch() method take two arguments to help you track and investigate errors, error – the error instance itself, and info which contains the component stack trace or the path in the component tree leading up to the offending component. The component stack trace contains helpful information for sorting and resolving errors. The componentDidCatch() method and Error Boundary work like try/catch statements for your React components. They provide a more consistent and dependable way to catch and deal with errors.

Note: Error Boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.

New Return Types

React 16 supports new return types that let your render less DOM nodes. For example, React no longer requires that the render() method returns a single React element. You are able to render multiple sibling elements without a wrapping element by returning an array. The other new return types React 16 supports are strings and numbers. Eliminating divs or any extra element added just to wrap your React component tree or returned content leads to overall cleaner and smaller components.

Render Children into Other DOM Nodes with Portals

React 16 introduces a new way of rendering into the DOM. You can render children into a DOM element that exists outside of your apps main DOM tree with a new feature called Portals. For example, in your index.html template you will usually have a div with the id root which is where your entire app is rendered into the DOM via ReactDOM.render. To create a portal, you add a second element that’s a sibling of your root div as shown below.

<div id="root"></div>
<div id="my-portal"></div>

Then you can render specific parts of your component tree inside the sibling div with the new createPortal() function. The createPortal(child, container) function accepts two arguments, child and container. The first argument child is the content you want to render. The second argumnet container is the DOM element where the content is going to render. createPortal() provides a hook into HTML that’s outside the root div. As mentioned in React docs, portals are useful when a parent component has an overflow hidden or z-index style, but you need the child to visually break out of its container. So a handy use case for portals is when creating modal windows or overlays. What’s interesting about portals is that the components they render are recognized as regular child components of the app. In other words, even though portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. For example, an event triggered from inside a portal still propagates or bubbles up to the parent component.

Returning null from setState

React 16 lets you decide if state gets updated via setState to prevent unnecessary DOM updates. In your events you can check if the new value of the state is the same as the existing one. If the values are the same, you can return null. Returning null will not update state and trigger a re-render. React 16 provides state performance improvements that let you prevent an update from being triggered by returning null for setState if the new value of state is the same as the existing value. Preventing unnecessary state updates and re-renders with null can make your app perform faster.

So these are some of the most important updates to React 16. Now there are a few other features I didn’t cover above like support for custom DOM attributes and Better server-side rendering. Finally, as with many popular JavaScript libraries, React is going to be updated frequently. Happy Coding!!!

Resources

Asynchronous Programming – The End of The Loop

To become an effective JavaScript programmer, it is important for a developer to learn how to develop and maintain asynchronous programs. JavaScript is a single-threaded programming language due to which applications written in JavaScript must use async APIs to stay responsive to user inputs while performing long-running tasks such as making a request for data from a server or running animations. You can’t get very far in a JavaScript code base without running across an asynchronous API.

Asynchronous programming may seem intimidating. How can we write programs that accepts input from the user, runs an animation, and sends a request to the server over the same period of time? How do we keep the code base clear and concise? How do we gracefully propagate and handle asynchronous errors? How can we avoid memory leaks caused by dangling event handlers? The different kinds of loops i.e. `for`, `for/in`, `while` and `do/while` and `try/catch/finally` statements in JavaScript are no help since they only work on synchronous functions.

Asynchronous programming is much easier than it seems and the key to it is to think differently about events. By using a handful of simple functions it is possible to build asynchronous programs. The first secret towards mastering asynchronous programming is learning to write programs without making use of loops. JavaScript loops can only work synchronously, and therefore cannot be used to repeat asynchronous functions. In order to gain expertise in asynchronous programming we must first learn how to code without making use of loops.

In the upcoming 9 posts to follow we will learn how to program Arrays without loops using just a few simple functions. We will learn the correct approach towards asynchronous programming and avoid making common mistakes. By the end of these 9 posts we will have the tools, concepts, and libraries required to be an asynchronous programming expert!

An Introduction to Yarn Package Manager

In this post, I will introduce you to the Yarn package manager. I will show how to integrate Yarn in your workflow and how to take advantage of its faster performance and consistency. NPM transformed the way we download, install and manage our application’s dependencies. But as you know it is not a perfect tool, even if there was such a thing. It’s slow and inconsistent and it has some security concerns as well. Well Yarn aims to fix that. Over the next few minutes I am going to introduce you to Yarn: A new package manager for JavaScript. Now lets get this out of the way Yarn does not attempt to completely replace NPM. Yarn is a new command line interface designed by the people at Facebook, Google, Exponent and Tilde and it fetches packages from the NPM registry. But it will replace NPM’s command line interface allowing you to do anything that the NPM Client provides.

Getting Started with Yarn is straightforward and of course the first thing that you need to do is install Yarn on your system. Visit Yarn’s website @ https://yarnpkg.com/ and then Click on Install Yarn button. This is going to take you to the installation instructions @ https://yarnpkg.com/en/docs/install for Yarn on your Operating System. Now Yarn needs NodeJS installed. More specifically, it needs NPM. So a lot of these installation instructions are solutions that will also install Node for you. For example, if you are on macOS by using Homebrew you can install Yarn which will also ensure that NodeJS is installed if it’s not already. If you are on Windows, if you install via Chocolatey then it will also ensure that NodeJS is installed. But if you download the installer be sure that NodeJS is installed first. Now this is just one way and chances are very good that you already have NodeJS installed on your computer. So you can install Yarn through NPM. Basically,

$ npm install -g yarn

and that’s going to give you the Yarn CLI. Once you have this installed then all you need to do is use the Yarn command and we will go over the commands that will be replacing NPM in your workflow because that’s essentially what Yarn is going to do. Now when creating a new project the first thing we do is initialize it with npm init and then we go through the process of answering questions and then we end up with a package.json file. And we essentially do the same thing with Yarn. Enter yarn init within the root of your project directory and then we answer the same questions. Now the interface looks a little bit different. Now we still end up with the same package.json file. So let’s say that we want to add React to our project. With NPM you would enter npm install –save react react-dom. With Yarn, we enter the command yarn add react react-dom. Saving is the default here. So we don’t have to say/enter that we want to save it. It is going to be default and it is going to download those dependencies for us. And it’s also going to be faster too because that’s one of the nice things about Yarn.

It’s performance actually comes from 2 separate things. The first is that everything that we install is going to be cached on our system. So whenever we want to install it with another project the first thing it is going to do is check to see if there is a new version. If it’s not new then it is going to use what we have in our cache and that is of course going to be much faster then it is by downloading it over the wire. But the second thing is that Yarn processes in parallel, NPM does not. NPM does things serially which makes sense if one task dependent upon another. But that’s not the case a lot of or even most of the time. So Yarn processes things in parallel which of course is going to be faster. Now I just added react above. Let’s remove that and we would do so by entering yarn remove react react-dom within the root of your project directory. It’s going to remove those packages. But now let’s add them. Let’s say we want to add a specific version, for e.g., version 15.3.1 of react and react-dom. So we will enter yarn add react@15.3.1 react-dom@15.3.1 and that will install that particular version for our project.

Once this is done installing, we are going to look at not just the package.json file but another file called yarn.lock. Because the yarn.lock file is very important with Yarn. First of all the package.json file is standard. We have the dependencies listed as well as their versions. Now one of the problems with NPM is that whenever your committed this to your repository and somebody else cloned it and did npm install and of course it is going to install the dependencies but you aren’t always guaranteed to get that exact version. In some cases, it might download a patch for that version which then you have 2 people working on essentially the same project but using different dependencies and that is a huge problem. So the folks that created Yarn decided to create this lock file. If you look at yarn.lock, the very first thing it says THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. This is created by Yarn whenever you install dependencies and it specifies the package as well as the version. So this is the file that you definitely want to commit to your repository because then whoever installs the packages using Yarn is going to get the same exact packages that are mentioned within the lock file. So if you look into yarn.lock file you will see both react & react-dom of version 15.3.1 installed.

Let’s say we are ready to update to version 15.4.0. For that we enter yarn upgrade react@15.4.0 react-dom@15.4.0 and this is going to update just those dependencies. Looking back into yarn.lock you will see those updated version numbers. So anytime you add, remove or upgrade a package, Yarn is going to update the lock file so that all the versions for all the dependencies are going to be consistent for everybody working on the same project and that is extremely important. That is also the main reason why Yarn was created to begin with. Now its worth noting that the packages that Yarn installs are from the NPM registry. There is not this new registry that have yarn packages. It’s using NPM. So in that sense there are a lot of related commands that are the exact same as NPM.

For example, we have already seen yarn init. There is also link, there is outdated, publish, run, cache clean, login, logout and test. All of these are the same commands as you would run with npm. However, Yarn has few things which NPM does not. For example, if we wanted to inspect all the licenses of our dependencies we would enter yarn licenses ls and it would list all our dependencies, their versions, their license and the URL for their repository. We can also generate our license dependency disclaimer by entering yarn licenses generate-disclaimer and that would generate that disclaimer. Finally, we can find out why we have a particular dependency. For example, let’s say we have a dependency called promise and so using  yarn why promise we can see why we have this promise dependency. Running yarn why promise gives us one of the following info i.e. This module exists because “react#fbjs” depends on it. 

We live in a world where there are new tools released almost on a daily basis and many of those tools are questionable. I mean there is no question that they are useful but you have to question whether or not it’s something that you want to spend time on. Well, Yarn is not one of those tools. Yes, it replicates NPM’s functionality  but it also brings some very useful things to the table. I mean the performance alone is the reason to use Yarn. So install it today and use it in your workflow.

React Life Cycle

This post covers some of the key concepts in React – props, state and keys. Then I will talk about React’s multiple life cycle functions which give us hooks for initializing our components and attaching behaviors at specific points in time.

Data for a given React component is held in two places, props and state.

Props is short for properties. We can think of properties a lot like HTML attributes. Props allow us to pass data down to child components. Props are immutable since they are passed down from the parent, they are effectively owned by the parent.

State in contrast is mutable and since state is mutable we should only strive to utilize state on our controller views. In other words, only use state on the top level components. Pass data down to your child components via props.

getInitialState – We can optionally define a getInitialState function. In this function, we can set the initial state for our component. This should typically only be done in the top level component, also known as our controller view.

getDefaultProps – We can also define default values for properties on our components using the getDefaultProps method. Inside this method, we can return a set of properties that our component should use by default if the parent component doesn’t declare a value.

React’s Life Cycle Methods

componentWillMount
When – Runs immediately before initial rendering. Runs both on the client and server.
Why – This function is a great spot to set the component’s initial state.

componentDidMount
When – Runs immediately after render.
Why – By the time this function is called, the component’s DOM exists. So this is a handy spot for integrating with other frameworks such as third party component libraries. This is also a good spot to set timers and make AJAX requests since you now know the component is rendered in the DOM.

componentWillReceiveProps
When – Run when the component is receiving new properties. In other words, when properties have changed. Not called on initial render.
Why – This is a place to set state before the next render since this runs just before the new properties are received.

shouldComponentUpdate
When – Runs immediately before render and when props or state are being received by your component.
Why – The big reason this function is useful is for performance. Why? Well, sometimes props and/or state changes, but the component doesn’t actually need to re-render because the data change doesn’t affect the DOM. When this is the case, you can return false from this function to avoid an unnecessary render call.

componentWillUpdate
When – Runs immediately before rendering when new props or state are being received. Not called on initial render.
Why – This function is a useful place to prepare for an update. However, do note, we cannot call setState in this function.

componentDidUpdate
When – Is evoked immediately after the component’s updates are flushed to the DOM. Not called for the initial render.
Why – This function allows us to operate on the DOM immediately after the component has been updated and re-rendered in the DOM.

componentWillUnmount
When – This function runs just before the component is unmounted/removed from the DOM.
Why – This is a great place to cleanup by destroying any related resources or DOM elements that were created when the component was mounted.

Keys for Dynamic Children

When creating multiple child components dynamically, we need to provide a key for each child component. The key is often the primary key for the corresponding database record, but it need not be. We just need to declare a unique ID for each specific record. As child components are added and removed, React uses this key to assure that child components are properly reordered or destroyed.