Search

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`}</h1>;  }  ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (  <div>  <button type="button" onClick={increment}>Decrement</button>  <span>{value}</span>  <button type="button" onClick={decrement}>Decrement</button>  </div>  );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`}</h1>;  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from https://nodejs.org/en/. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (  <div className="counterContainer">  <button type="button" onClick={decrement}>  - </button>  <span>{count}</span>  <button type="button" onClick={increment}>  +  </button>  </div>  );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
What Is a React Component? Write Your First React Component
Pavan
Rated 4.0/5 based on 15 customer reviews

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root"));Alright. But is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { }, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (    Decrement  {value}  Decrement    );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`};  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from https://nodejs.org/en/. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (      -   {count}    +      );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
Rated 4.0/5 based on 15 customer reviews
6721
What Is a React Component? Write Your First React ...

Prior to ReactJS, Popular frameworks like Angular... Read More

Overview of Modules in Node.js

Node.js is an open source, server-side runtime environment which runs on various platforms like Windows, Linux, Unix and other operating systems. Node.js is built on JavaScript engine and provides ability to build scalable applications. The runtime environment is event-driven and provides asynchronous programming which is memory efficient. Node.js is useful in generating dynamic page contents as it eliminates the need for the wait to open and close files and continues with the next request. We can also use Node.js to modify data in our database. In other languages, it’s usually better to structure our application code and break it into small pieces. However, in ode.js, we can write all our application code in one index.js file, irrespective of the complexity of our application, and the node.js interpreter will not cause issues. But, if we have very complex application, it would be better to divide our application code into small modules and then combine them into a cohesive application. Introduction to Node.js Modules Node.js modules are the different functions which can be reused time and time again. They can be organized into single or multiple JavaScript files in the same or different folders. Each file is treated as a single module. They can also be considered as JavaScript libraries. Every module has its own context and does not interfere in the working of another module. Together, these modules help to run the application.  Before we deep dive into types of modules, let’s take a quick example of creating a simple module.  const average = (a, b) => {return a + b;}; const output = average (2, 3)console.log(output)The above module will calculate the average of two numbers and display the output. Types of Node.js Modules Built-in Modules When we install node.js, several lightweight modules are automatically created, which provide bare minimum functionalities.  These modules are compiled into the node.js binary. They are also referred to as core modules and located in the lib folder. Below are few of the built-in modules in node.js   ModuleCommentsurlUsed for url parsing and resolutionpathIt is used to deal with file paths using methodsfsIt is needed to work with I/OutilIt includes utility functions needs by programmers.httpIt is used to create http server using classes, methods and events.These modules are used in our application code as reference. The code of these modules are not part of our program as they work as libraries. They are always loaded if their identifies is passed to require().  Let’s see an example:var URL = require('url').URL;Here require(‘url’) is what gives us access to url module. The definition of url module is not seen to us. We just need to understand when and how to use it.  Built-in functions have methods and classes which can be used when we require() the module.  For example:var http = require('http');   http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});   res.end ('Welcome to Node.js Modules!');   }).listen(8080);Here, we use the http built in module using the require(‘http’). Once we load the http module, its classes and functions like createServer can also be used.  External Modules Node.js has a huge open source community which really boosts its ecosystem. People from around the globe contribute to the node.js community, which provides access to various modules other than the built in modules. These modules are created to solve specific problems in specific environments and then open sourced for the benefit of others. Since these modules are not part of the library, they cannot be used directly using the require unless we first install the codebase containing the module locally; once this is done, they can be integrated to our codebase. External modules are also known as third party modules and require a package manager that maintains all the modules so that they can be accessed with ease. By default, node.js uses NPM [node package manager) package manager for JavaScript runtime environment. NPM is primarily used to install and maintain external modules in node.js application; we can install the external modules which are needed for the application using NPM. Custom Modules Built in and External modules are provided by others based on their needs. However, there might be cases where you need to build your own module for your application.  Let’s create a module of our own named mydiffreturn Math.diff() * (max - min); } exports. between1and10 = function () { return getdiff (1, 10); };We will put this code in a separate file called mydiff.js which provides helper function that returns a difference of two numbers. This file can provide attributes to the outer world via exports, then index.js can use the exported functionality.   Below is the content of index.jsvar mydiff = require('./mydiff.js'); console.log(mydiff.between1and10());require () will again come into play by making the attributes of local mydiff module available. Module can also allow hiding to hide the functionality of the module which is not needed outside of the module. This can be done simply by not exporting the functionality via exports. In such case even though we will have mydiff.js file specified in index.js it will not be able to access the non-exported function and fail with the following error.  TypeError: mydiff.getdiff is not a functionThis way, we can keep our codebase more organized by hiding the implementation details in a module and exposing only those parts which will be used by other parts of the codebase.  Module Caching When the modules are first loaded, they are cached. This means every call to the require () will get the same object returned for multiple calls if the call is resolved to the same file. This is an important feature as it allows us to load the transitive dependencies for returning partial objects. Module caching is done in an object in a key-value pair and then we can reference the objects using the cache (require.cache). If we delete any key from this object, then we need to reload the module on next require () call. Caching Modules also have some caveats as the modules are cached based on their filenames. If a module is resolved to a different filename based on the location of calling module it is not guaranteed that require () will always return the same object. Also, in case of different case-insensitive file systems, different resolved file systems points to the same file. In such a case, again, cache will treat them as separate which will result in reloading the module multiple times. For example, require (‘. /mydiff’) and require (‘. / Mydiff’) would result in two different objects. Stateful & Stateless modules If a node.js module exposes an instance of some stateful object like db connection or socket etc., it is stateful module. Whereas, if a module exposes stateless entities like classes, methods etc., then it is known as stateless module. If an application codebase uses stateful module, we should follow the singleton pattern so that all other modules requiring stateful module access the same instance. Due to the concept of CommonJs system we don’t have to explicitly wrap our stateful module in Singleton pattern. The first time we use the module, it will be cached for the subsequent require as while caching, node.js uses instance package address as a key. Stateful modules should be used with more caution than stateless modules if used in the tightly coupled architecture. Module Dependencies Any component or piece of information that is needed for the working of the module is regarded as dependency, but the first thing that comes to mind while thinking about the dependencies of node.js is the content of the node_modules folder. From database connection instance to string with file path can be considered as dependency. In a broader classification, dependencies are divided as ‘hardcoded dependency’ and ‘injected dependency’. If you hardcode the name of the dependency inside the module using a require function in the wiring pattern, it is referred to as ‘hardcoded dependency’. If the name of dependency is instead provided as input by external entity, then it is known as ‘dependency injection’. Let’s see some differences between hardcoded dependency and dependency injection. Hardcoded DependencyDependency injectionThey are intuitive and easy to understand.Offer higher reusability.Easy to debug.Difficult to debug.Offer less flexibility as they are tightly coupled.Dependencies are wired at runtime.Unit testing is harder since dependencies are hardcoded.Unit testing is easyConclusion To understand how node.js modules work, we need to know the various functionalities it offers. With this objective in mind, we first looked at the different types of node.js modules. We then explored built in modules, looking at different types of modules and examined what they offer and the advantages of having these modules.  We then saw External modules and walked through how they can be included in our codebase, including how the module code could be hidden if we so wished. Finally, we saw custom modules, their benefits and how to use them effectively. We examined how modules can be cached in modules providing us with performance gains by avoiding reload several times, while also going through some caveats we should be aware of.  We also saw how modules can be stateful and stateless and where both can fit in. Finally, we explored the module dependencies and few differences between them which helps us choose among them as per the need of the application.
Rated 4.0/5 based on 15 customer reviews
6519
Overview of Modules in Node.js

Node.js is an open source, server-side runtime ... Read More

How to Update Document in MongoDB

MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. Updating Single document Syntax: db.collection.update(query, update, options) Use the update method  Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. Use the $set operator to update the values  Choose the Field Name that needs to be updated and enter the new values accordingly –  Employee_Name =”Daniel Morales”db.Employees.update( {"Emp_ID" :100}, {$set:{"Employee_Name" :"Daniel Morales"}}); WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })Updating Multiple documents Syntax: db.collection.update(query, update, options) For updatingmultiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time. The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. Use the update method  Specify the condition which you should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. Use the $set operator to update the values  Choose the Field Name(s) that needs to be updatedand enter the new values accordingly – Employee_Name =”Nandan Kumar” Emp_ID = 21db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})MongoDB save() Method  The db.collection.save() method is used to update an existing document or insert a new document Syntax: db.collection.save() db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({“ nInserted" : 1 })The save() method returns a WriteResult object which contains the status of the insert or update operation. During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:db.Employees.find(); {"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . Note -  If the document doesn’t contain an _id field, then the save() method calls the insert() method. db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})The save() method performs an update with upsert: true since the document contains an _id field:  db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })Note -  If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : MongoDB updateOne() method This method updates a single document within a collection matching the filter or condition. Syntax The syntax of updateOne() method is − db.collection.updateOne(, ) Example> db.Employees.updateOne( {First_Name: 'Nandan'}, { $set: { Age: '30',e_mail: 'nandan@gmail.com'}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }MongoDB updateMany() method The updateMany() method updates all the documents within a collection based on the filter or condition . Syntax : The syntax of updateMany() method is − db.collection.updateMany(, ) Example>db.Employees.updateMany(  {Age:{ $gt:"25"}},  { $set:{Age:'12'}}  )  {"acknowledged":true,"matchedCount":2,"modifiedCount":2}Using the find command, you can retrieve the contents of the documents:> db.EmpDetails.find() { "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345" } { "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" } { "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update( {type:"FullTime"}, {$set:{salary:20000}}, {upsert : true} )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the Write Result of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection. Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . This command works as both updateOne and updateMany command. db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    } )Here, it will update only first document which matches the condition.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" },    }, { multi: true } // Additional Parameter )Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .db.collection.updateOne() --> method to update only one document in a collection.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated      } )This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False.You can also update multiple parameters but they need to be separated by a comma (,). E.g.$set: { "bonusEligiblity": "False" , “emp_status : ”New”},db.collection.updateMany() --> method to update multiple document in a collection matching the specified conditiondb.Employees.updateMany(    { "joinYear": "2020" },   { $set: { "bonusEligiblity": "False" },   } )Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update(      {type:"FullTime"},      {$set:{salary:20000}},      {upsert : true}   )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the WriteResult of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.Conclusion   To summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed. db.collection.update(query, update, options) In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function. Hope this has been useful. The MongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding! 
Rated 4.0/5 based on 13 customer reviews
7904
How to Update Document in MongoDB

MongoDB provides the update() method to update the... Read More

AngularJS: Top Use Cases and Reasons to Opt for This Tool

AngularJS represents a structural framework for dynamic web applications. It is an open-source, JavaScript-based front-end web platform primarily developed by Google and a consortium of individuals and companies to solve many of the challenges faced in the development of single-page applications.   AngularJSAngularJS offers flexibility in coding like no other framework due to its simple design architecture. In terms of simplicity, it helps beginners to get started and make improvements to their application projects easily. AngularJS also handles heavy web applications that are exceptionally well loaded with features and components. It allows you to use HTML as your template language and allows you to extend the syntax of HTML to clearly and succinctly express the components of your application. The data binding and dependency injections ensure that we do not need to write a big chunk of code which otherwise we would have ended in writing. And all happens inside the browser making it a perfect partner for any application. The next layer data binding frameworks gains popularity due to strong demand. The foremost known ones are: AngularJS KnockoutJS BackboneJS DurandalJS JavaScriptMVC AngularJS overview AngularJS is a platform and framework that uses HTML and TypeScript to build single-page client applications. The below diagram will give you fair idea of difference in traditional page life cycle vs Single page life cycle : AngularJS overviewThe AngularJS application is written using typescript. It introduces core and optional features when you import a collection of TypeScript libraries into your applications. The architecture of an AngularJS application is based on some fundamental principles.The basic building blocks are NgModules which provide the component compilation background. NgModules compile the related code into functional sets; a collection of NgModules define an AngularJS application. An AngularJS application often has at least one root module that enables bootstrapping, and usually has a lot more feature modules.We will not go into details as this is out of scope of this article but to give you better understanding of an AngularJS application ,let's look at below example where we are trying to calculate area of rectangle :  Area:     Width:     Breadth: Area: {{width * breadth}} This appears to be normal HTML, with some new markup. A file like this is called a Template in AngularJS. Once AngularJS launches the code, it uses the compiler to interpret and process this new markup from the template. The DOM that is loaded, transformed, and rendered is then called view. The Directives are the first kind of modern markup. We add special actions to items or attributes in the HTML. You would have noticed the new attribute ng-app which is a directive for initializing AngularJS apps automatically.AngularJS also defines an input element directive which adds additional behavior to the element. The directive ng-model stores / updates the value of the input field within / from a variable. Why AngularJS? AngularJS is backed by Google. This is a huge relief for developers to operate on a stable code base that will offer the application maximum support. it's a stable platform to focus on. Many frameworks are nowadays a pure bundling of existing resources. They are an integrated group of tools but they are not very elegant. AngularJS is the next generation platform where each tool was built to function in an integrated manner with any other tool. Please find below some reasons why AngularJS is considered as best among its competitors: MVC inbuilt support Most frameworks enforce MVC by asking you to break your app into MVC components and then allow you to write code to re-string them. This is a lot of work. As a developer we have to just split the framework into MVC components and leave everything to AngularJS for taking care. Declarative User Interface AngularJS uses HTML to describe the user interface within the program. HTML is a more concise and less complex declarative language than the procedural interpretation of the JavaScript interface HTML is also less brittle to reorganize than a JavaScript-written GUI, so things are less likely to break. And when the view is written in HTML, you can put in a lot more UI developers. Data models are POJO The POJO acronym for plain old java objects are being used as data models in AngularJS and it works without superfluous functions getter and setter. You can include and change properties straightforwardly and circle over objects and exhibits voluntarily. Your code will look a lot of cleaner and progressively instinctive, the way mother nature expected. Behaviors with Directive Directives are the way AngularJS brings added functionality to HTML. Imagine a world in which HTML has so many rich elements ( e.g. < accordion>, < grid>, < lightbox>, etc.) that we never have to manipulate a DOM to simulate them.To get some functionality out of the box, all that our app needs to do is assign attributes to items. Flexibility with filter Before displaying data on UI, filters filter the data and may include anything as simple as formatting decimal places on a list, reversing the order of an array, filtering a parameter-based array, or implementing pagination. Filters are designed to be stand-alone features, similar to instructions, independent from your device, but concerned only with data transformations. Less code All the points you have received up to now mean you 're getting to write less code. No need to write your own MVC pipeline. The view is described using more succinct, HTML. Without getters / setters, data models are easier to write. Data-binding means you don't have to manually insert data into the view. Also the directives are different from the software code, they can be written in parallel with limited integration issues by another team. Filters let you manipulate view level data without changing controllers. Unit testing ready The definition of AngularJS would be incomplete without speaking of its readiness for unit test. Dependency Injection (DI) links the whole of AngularJS together. Agular's unit tests will use dependency injection for unit testing .It mocks the data and injects into server. In reality, AngularJS already has a mock HTTP provider for controllers to insert fake server responses. It beats the more conventional way web apps are checked by creating individual test pages that activate a single feature and then communicate with it to see if it is working. Google assisted, and a great community of growth. Supported by IntelliJ IDEA and Visual Studio .NET IDEs. Limitations AngularJSis not a magic bullet. Some of its drawbacks are the backsides of its positive points, some of which are intrinsic to JavaScript inefficiency that could not be solved even with the strongest derivatives of its limitations are listed below: AngularJS is broad and complicated. With multiple ways to do the same thing, it's hard to tell which way is best for a particular task. Mastering AngularJS at the "Hello World" level takes significant effort. Different developers' coding styles and habits can complicate the integration of different components into a complete solution. When the project expands over time, you will most likely need to throw away current implementations and build new ones using different approaches. AngularJS implementations are poor in scale. More than 2,000 watchers will seriously lag behind the UI. This limits the complexity of your AngularJS forms , especially large data grids and lists. Best use cases of AngularJS If you want to build smart lightweight applications, AngularJS is your best bet. This TypeScript-based framework helps you to build interactive SPAs that are safe, maintainable, and easy to check. Some of the popular use cases for AngularJS are as follows: YouTube PlayStation three app for video streaming Anyone who likes to play video games would not have skipped the PlayStation 3 version of YouTube. Considering the vast popularity of YouTube, a structure will be needed. Because Google owns AngularJS, it has been leveraged to introduce a brand-new version of YouTube on PlayStation 3. The flexible architecture has helped Google reinvent the PS3 experience by replacing the traditional operating method with a fully new one.  They replaced mouse movements with basic keystrokes. With AngularJS usability, the features of native apps like YouTube PS3 can be extensively leveraged.AngularJS has made a greater contribution in playback video and smooth scrolling on the YouTube PS3. It's the latest ultra-modern and seamless experience of AngularJS, experienced by the crowd of gamers. eCommerce applications like T-Mobile T-Mobile discovered that its customers had to wait for content to be loaded while connecting to the app. So, to make it quicker and less complicated, they used AngularJS server-side rendering to reduce the time. They also used AngularJS so that they could use HTML parsing for search engine purposes.  This leading telecommunications leader has had tremendous success in their eCommerce app, which has generated a phenomenal search engine traffic. With AngularJS, the application interface has been revamped and turned into a smooth and powerful app. Real-time Data Application like weather.com Weather.com is one of the most popular real-time weather update websites. The credit for its success is given to AngularJS 's modular functionality of modules and directories that enable you to use the features of the app on mobile and smartphone devices.  The framework enables developers to build customizable widgets based on the device's specific needs. Using real-time data and dynamically presenting it made it available on the Web using AngularJS technology. What projects don’t need AngularJS AngularJS is super heroic, but there are situations where you can't use AngularJS. Websites with Static Content Small websites with lower targets and static content. These types of websites are better built with limited technical stacks and do not need to be used by AngularJS, as the technology will only add extra pieces of code that are not required by the website or a specific project. Example: landing pages, educational websites, event pages, etc. Limited Resources and Startups AngularJS is not a good idea to start with for small teams and limited resources. AngularJS needs the skillful tools necessary to solve fast problems in large-scale projects. Technology should also not be used for small projects; it can be developed with other available frameworks and does not require much technological facilitation. Game Apps and Heavy Analytical Apps AngularJS is not a gaming app. Other frameworks, such as React, can be used to build a highly interactive UI in games. AngularJS tests every document object model before it changes its position. It is not recommended to use AngularJS in any app which require strong complex mathematical analytics mostly which is used in gaming. Popular web apps built with AngularJS Sharing a list of some of the renowned web applications that are driven by a versatile and robust AngularJS framework: The Guardian The Guardian is a leading designer and publisher, winning a variety of competitions in these fields. The Guardian website UI is created as an AngularJS app.Guardian.com PayPal Papal is one of the world's largest Internet payment firms. This is another one of the big websites that use AngularJS.Paypal.com JetBlue JetBlue is one of the most famous airline companies in the United States as the online airline portal. The new edition of the JetBlue website uses AngularJS.Lego Lego is one of the world's leading producers of play materials. Its products are traded global and can be virtually explored at www.LEGO.com.Lego.com NetflixNetflixNetflix is an American MNC entertainment company. It focuses on and offers streaming media and video on demand online and DVD by mail.FreelancerFreelancer.com Freelancer – the global leading online workplace where understanding businesses and professional service provider go to work!WeatherWeather.com Weather.com is one of the top weather forecasting online report websites. It is also one of the biggest websites using AngularJS.YouTube for PS3YouTube App on PlayStation Owned by Google, YouTube is mainly used for video hosting and sharing. This is being developed using AngularJS framework. Conclusion We can conclude that the AngularJS web app development framework surely has a wide range of powerful features that gives AngularJS an edge over its competitors like ReactJS. This is one of the primary reasons large-scale businesses are opting for AngularJS as their preferred choice of web development platform. To summarize the key points about AngularJS. It is easy to learn and master. It makes application stable and fast. A bunch of useful features in one framework. There are tons of reasons why you should choose AngularJS for your next web app. The World loves it. We mastered it.
Rated 4.0/5 based on 13 customer reviews
6721
AngularJS: Top Use Cases and Reasons to Opt for Th...

AngularJS represents a structural framework for d... Read More

Advantages and Disadvantages of Angular

What is Angular? Angular is a frontend web application development framework based on TypeScript, built by folks at Google and heavily contributed to by a huge community of developers around the world. It is a Single Page Application (SPA) framework, which means that Angular is capable and is primarily used to build single page web applications or SPAs.Angular logoAngular is developed by the same team of individuals that developed the popular framework AngularJS. The modern Angular requires you to have knowledge of the Typescript language which is a strict syntactical superset of JavaScript and adds optional static typing and some other features to the language that otherwise JavaScript lacks. The AngularJS framework was re-written and called "Angular 2", but this led to a lot of confusion and panicwithin the developer community. To clarify, the Angular team started to use separate terms for each framework. At this point, "AngularJS" now referred to the 1.X versions and "Angular" without the "JS" referred to versions 2 and up. Since then, all the versions of the framework other than 1.X are just called Angular. You can, however, mention the version number to be more precise. TypeScript is designed for development of large applications and transpiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. So, you can still use JavaScript in your TypeScript code files, but please do not do that. In this article, we will take a closer look at how Angular has evolved into one the mostpopular web development frameworks and understand its pros, cons, features and more. We will leave you with a few quick tips and suggest how you can get started with understanding Angular indepth to achieve mastery over the subject. History of Angular AngularJS was the first version of the framework, created by Google, that first came out in 2010and it shook the developer community. There were so many amazing features that AngularJS offered. Most talked and loved of all the features that it offered was two-way binding between the view and the model.  So, it let us developers get rid of a lot of useless code to set up bindings and keep the view and model in sync at all times. AngularJS was golden. AngularJS became very popular within the developer community and was widely adopted.It received a lot of traction. Still, the team decided to take another step further and developed a new version which was initially named Angular 2 but later was called Angular without the “JS” part. Soon after, in 2014, Angular 2.0 was announced which was a complete rewrite of the framework from scratch and unlike AngularJS that used JavaScript as the primary language, it used TypeScript. A final version of the framework, Angular 2, was released in 2016. Later, it was renamed to Angular to avoid conflicts and confusions within the developer community.  A lot of new changes were brought in and developers had to learn it all over again which was a tough change but was welcomed by the community. Angular opted for semantic versioning and from now on, all versions of Angular will just be called Angular. Near the end of 2016, Angular 4 came out (yeah, they skipped Angular 3 to avoid some conflicts and confusions). With a few more major versions and performance upgrades in each version, we have now arrived (at the time of writing of this article) to Angular 9.  Angular 9 has better than ever performance and latest features. In these intermediate versions, there have been updates to the performance, CLI features, progressive-web app features, router, and a lot more. They even upgraded to a better rendering engine in Angular 9. Angular 10, a major upgrade to the popular web development framework, has reached the release candidate stage, with six release candidates published as of June 17, 2020. The upgrade to the Google-developed, TypeScript-based framework focuses more on ecosystem improvements than new features. Advantages of Angular Angular hascome a long way since 2012. There are benefits to using the framework and there are some drawbacks as well, especially if you are a beginner. Let us talk about the good things first. Maintained by Google The best things about Angular is that it is developed and maintained by Google. As it is backed by a trusted company, trust is well established within the community. Developers believe in the framework and in the fact that it will be maintained, and issues will be resolved, of course withthe help of community contributions. Large community and ecosystem Angular is actively maintained and has a large community and ecosystem. You can find lots of material on this framework as well as many useful third-party tools. Currently, Angular has around over 63K stars on GitHub, a clear indication of the popularity of the framework. Github   Two-way Data binding Two-way data binding in Angular will help users to exchange data from the component to view and from view to the component. It will help users to establish communication bi-directionally. Two-way data binding can be achieved using a ngModel directive in Angular. This ensures that the model and the view are always kept in sync without any extra effort. Use of TypeScript Angular opted for TypeScript as the primary programming language. TypeScript adds a lot of syntactic sugar to JavaScript. With TypeScript, we also get several productivity benefits. In editors like VS Code and WebStorm, we have access to robust code help (intellisense) as we type, making it easier to discover types, the features they offer, and most importantly the common syntactical errors.TypeScript is a typed superset of JavaScript that compiles to plain JavaScriptSupport for i18n Internationalization is the process of making sure that an application is designed and prepared to be used in regions with different languages. Localization is the process of translating your internationalized app into specific languages for particular locales. Angular can take care of most things when it comes to multiple languages. Dates, numbers, times, and other things are easily taken care of based on the locale. On top of that, the Angular CLI allows us to install the @angular/localize package and generate most of the boilerplate code necessary. Support for lazy loading An Angular module is a logical unit of code that performs a certain task or takes care of a certain responsibility in the application. A normal Angular application can be broken down into multiple modules, where each module is delegated a certain responsibility. A module can comprise of components, pipes, directives or more modules.  Breaking down an application into modules not only allows to easily manage an application as it grows, but also offers huge performance advantages. Instead of loading all the application code at once in the browser which may cause more loading time and a slower initial render of the web page, it loads only what is necessary. This is called lazy loading.  Only the modules that are required are loaded initially and more modules or rather chunks of code are loaded as an when required. This offers seamless performance and smaller loading times. Every Angular app has at least one NgModule class, the root module which is responsible to bootstrap the project. Conventionally, it is named AppModule and itresides in a file named app.module.ts.  Dependency injection Dependency injection or DI is one of the most important application design patterns and Angular has its own dependency injection framework. It is typically used in the design of Angular applications to increase their efficiency and modularity. This is closely related to the previous point - modularization of the Angular app.   Dependencies are services or objects that a class needs to perform its function. The class requests services from an external resource, generally another module or class in this case, instead of creating them themselves. This allows us to delegate single responsibility to each module. The advantage of dependency injection design pattern is to divide the task into multiple services. The class will not create the dependent object itself, rather it will be created and injected by an Angular injector. Dependency Injection is technique that is used to reduce the coupling amongst various components of an application. Looser coupling allows for better testability and maintainability. Powerful Router Routing or in-app navigation in Angular is taken care of by the Angular Router. It is a module available in the @angular/router package. Angular router is a very powerful and flexible navigational service. It usesa component called router-outlet to load various components into the view depending upon the URL in the browser.  Angular Router has built-in support for lazy loading components, so the modules are loaded from the server as the user navigates within the app. Huge apps have a lot of benefits because of this feature.  Support for Ionic Angular was the first framework that was supported by the Ionic framework. It allows building cross-platform mobile applications for Android and iOS using the Ionic components and Angular code. As of now, more frameworks like ReactJS and VueJS are also supported but still, Angular is widely used with the Ionic framework for mobile application development.Angular is widely used with the Ionic framework for mobile app developmentAvailability of packages There is a huge repository of open-source packages available for Angular developers. Some of the most important packages are NgBootstrap, Angular Google Maps, NgRx, NgTranslate, AngularFire, NgxTextEditor, Angular Material, Ng2 Pdf Viewer, NgxCharts, and many more. Some of these packages are maintained by the official Angular team and most of these are taken care of by the community of developers as well. It is most likely that if you are looking to build a complex feature or a component for your application, a package already exists for you, so why reinvent the wheel? Disadvantages of Angular So, we have seen the good things about Angular, but there is another side to the story as well. Let us talk about some of the downsides of using one of the most popular web development framework. Steeper learning curve While Angular is great, it may not be the case for a complete beginner. Even if you have experience with HTML, CSS and JS, you may feel a little bit uncomfortable with the steep learning curve that it has. It brings its own notions and philosophy to the table that you need to work around.  Angular is an opinionated framework which means that it has its own rules that developers need to learn and follow. This can be a good and a bad thing, but the learning curve can be uncomfortable for total beginners. I would recommend that you stay patient and start slow. Slow and steady! Limited SEO Capabilities Angular is just great for building powerful single-page web applications. However, as with all single-page web applications, there is a disadvantage when it comes to search engine optimization.   Usually single-page applications are rendered on the client side and therefore web crawlers of search engines like Google and Bing are not able to see the complete structure and content of the individual pages of the websites. With this limitation in place,it is not possible to list your website correctly in search engine results.  However, there are techniques and packages to make this work, but it is an extra effort in terms of development. Angular universal is a way to render the Angular application of the server itself. The technology enables server-side rendering for Angular applications. Angular Universal generates static application pages on the server through a process called server-side rendering. While Angular universal takes care of most aspects, it still requires a lot of setup. If you prefer to do it all manually, there are documents available to help you do that but there are gotchas that you need to watch out for. Too many versions Angular has been evolving. It started out as a JavaScript framework AngularJS and now the current version is Angular 9 with a total of 6 major releases in between. This can cause confusion especially for beginners. Many a time, beginners struggle to understand the versioning. I have seen students learning a version of the framework, latest at the time, and by the time they finish their first project, a new major release is out. This causes trust issues. Developers, at times, feel that they must keep working on their apps and resolve version conflicts and compatibility issues. Decline in popularity With the advent of newer frameworks like VueJS and ReactJS, Angular has seen a downfall in its popularity. Just a few years ago, developers were mainly debating on whether they should be using Angular or React for their projects. But over the course of the last couple of years, we saw a growth of interest in a third player called VueJS or Vue.js. While the job market in Angular continues to expand, it has been observed that the popularity of the framework has been declining. I believe that too many versions is one of the main issues that the framework needs to address. Lot of boilerplate code If you are building a simple app, there is a lot of boilerplate code that the application requires. Although with tools like StackBlitz, it has become easier to try code ideas and experiment without having to install anything on your computer, but if you decide to start developing an Angular app on your system, you need to install a bunch of things and the most simple “Hello World!” application will have a lot of code that you do not care about. What’s new in Angular 9? Let us take a closer look at what is in store for us in the Angular 9 version of the framework. We will delve into the latest version of Angular 10, released in June 2020, in a separate blog post. Step-by-step guide The official Angular website offers a step-by-step guide on how to upgrade your existing apps to the latest version. GuideIvy, the next-gen compilation and rendering engine Ivy is the code name for Angular's next-generation compilation and rendering engine. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine. You can, however, disable Ivy if you still want to use View Engine for your app. It is a huge milestone for the framework. Ivy offers faster build times and small build sizes. It also offers a new change detection system.The important point is that we don’t have to change how we write our applications. Ivy aims to be compatible with the existing applications. Ivy is going to be smaller, simpler, and faster as quoted by the Angular team.  In the demo shown by Miško Hevery, the creator of the AngularJS framework,in ngConf 2018, the Hello World application was merely 3.2KB which is significantly small although 3.2KB is the result after minification + gzip.Total bundle SizeIvy compiles one file at a time and therefore follows the locality principle. Ivy looks at a component's template when generating the compiled output. This process leads to faster compilation. Ivy makes sure that, if you are not using something in Angular, it does not get included. Since Ivy pipelining is simplified, templates will be part of the stack trace.  No more cryptic error messages when something is broken in our template syntax as we will see the exact line number where the error is. The Ivy compiler has been designed to remove parts of Angular code that aren’t being used via a mechanism called tree-shaking and to generate less code for each Angular component. With these improvements, small apps and large apps can see the most dramatic size savings. Angular ahead-of-time (AOT)  In Angular 9, AOT is enabled for Dev build as well. The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code.  Compiling your application during the build process provides a faster rendering in the browser. AOT allows faster rendering of the application and also makes sure that there are a lot less asynchronous requests. According to the docs, AOT compilation with Ivy is faster and should be used by default. Lazy loading components Before Angular 9, we could only lazy load modules. Now, you can also lazy load components. It is a great way to shrink the size of your main bundle and boost the initial load of your application. Lazy loading of single components has not been possible so far. But things have changed with Ivy.  Works with TypeScript 3.6 and 3.7 The latest version of the TypeScript is 3.7 and Angular 9 is updated to work with TypeScript 3.6 and 3.7. Angular 9 supports usage of the same TypeScript Diagnostics format for the TypeScript Compiler diagnostics, which will generate more descriptive error messages. According to the official docs - “In TypeScript 3.7, when opening a project with dependencies, TypeScript will automatically use the source . ts / . tsx files instead. This means projects using project references will now see an improved editing experience where semantic operations are up-to-date and “just work”. SupportscCSS variables or custom properties Angular 9 supports CSS variables or custom properties. CSS variables or custom properties allowsdevelopers to define their own variables for CSS values that can be shared between components and style rules.  CSS custom properties or CSS variables allow the CSS property values to be changed at runtime. The possibility that the CSS custom properties can be updated during runtimeopens the opportunity to easily create themes for newer Angular application.  Angular:Quick tips and facts Angular is a framework used for front-end development. This involves the client-side of the application and has little to do with the back end. Angular is best utilized for completing advanced, large-scale projects under the direction of a seasoned developer. Angular is created for enterprise-scale applications. Angular elements can be added to projects that were built using a different platform, such as React or Polymer. Angular is supported by Google. This program is not up to par with SEO best practices, so if your primary focus is search engine optimization, opt for a different platform. Angular is a JavaScript framework—not a JS Library.Angular ranked second in “most used technology” in the Stack Overflow Survey of 2018.  How to get started with Angular?Are you ready to take on the best and become a master of the Angular framework? Check out the Angular Training and Certification which comes with instructor-led live training and real-life project experience.  This training will help you understand Angular in-depth and help you achieve mastery over the subject. 
Rated 4.0/5 based on 14 customer reviews
12798
Advantages and Disadvantages of Angular

What is Angular? Angular is a frontend web applic... Read More

Introduction to Hooks in React

Technological change is rapidly impacting our present and our prospects for the future, and so are frontend frameworks, which are emerging at a very fast pace these days. And in many ways, React, the most popular framework amongst the JavaScript community, is turning out to be unstoppable.   Many of us have already played around with Hooks or have at least heard about them. But there are still many who are probably yet to take the time or have had the chance to experiment with them.  No worries, sooner or later you will find yourself diving into Hooks.  In this article, you will learn about the term, ‘Hooks’, and the reasons why you should use them in your future projects. Furthermore, you will learn about how you can use React Hooks in the best possible manner to build some awesome features in your projects and write cleaner code.  What exactly is a Hook? Hooks are just regular JavaScript functions. In layman terms, hooks provide a way to use functionalities such as context or state, which could earlier only be achieved through classes, and now can easily be done using function components. React Hooks enable functional components to attach local state with it, and this state will be preserved by React when the component re-renders. Hence, this allows React to be used without classes. While working with function components in React, we sometimes need to add state to it. In order to achieve that (to use setState() and states), we have to convert our function component into class one. With the help of Hooks, we can use the state in Function Components, without the use of classes. A practical view There are two approaches to create a React component. One is using functions and the other is using classes. There is always a question in mind that “When do I use one v/s the other?” Let us assume we have a simple class component and then we will convert it to a functional one with hooks and see the difference. Component without Hook: Class Componentimport React, { Component } from'react';  classGreetingextendsComponent {     state = {         text: ''”     }  handleChange= (e) => {  this.setState({ text: e.target.value })     }  render() {  return (                      )     }  }  exportdefaultGreeting; Components with Hook:Functional Component: import React, { useState } from'react';  exportdefault () => {  const [text, setText] =useState('');  return (         { setText(e.target.value) }}         />     );  }Advantages: Readable Lesser Code. Overall Optimized component Writing a Functional component with state Writing complex components became easier Handling events & logics in functional components. Performance boost up with Functional Components  If you disagree with any of the above, you can play with it in practice. I’m sure that would change your mind! Types of Hooks Now, let us understand the power of hooks with some cool examples that will describe some basic Hooks which are: useState() useEffect() Custom Hooks (Building Your Own Hooks) State Hook In React, we all are quite familiar with how the state is generally defined. If not, I’d recommend you to refresh your memory of State here. this.state= {     name: Steve Marley  }; While state issimilar to props, we know that state is controlled by a component. Traditionally, state is generally defined by writing a class where “this.state” is used to initialize a class. Let us take an example of class Component named (MyComponent): classMyComponentextendsReact.component {  constructor(props)  super(props);  this.state= {         name: Steve Marley     }  } In class components, it isreally hard to reuse stateful logic between components and complex class components become hard to read and even harder to understand!! React hooks help us to get rid of all that old-fashioned class stuff by making use of useState().  Now, this is important to note that in a functional component there is no concept of objects and objects being set as context (like we do in classes), so we can’t assign anything or read this.state. Instead, we call the useState Hook directly inside our functional component: This will become something like this: import{ useState } from'react'; // line 1  functionMyComponent() {  const [name, setName] =useState(‘Steve Marley');   // line 2  } Let us understand this code line by line: In line1: there is a new method imported here called useState. What is useState and how do we use it? Well, useState is the React Hook that will allow us to access and manipulate state in our existing component. Therefore, in this approach, we do not have to extend our Component as we did in previous code. And that’s it! It is worth noting that we are playing with states outside a class in the component directly as shown: import{ useState } from'react'; functionMyComponent() {  const [name, setName] =useState(‘Steve Marley’);  return              Heyyyyy!! {name}       }Deeper explanation In class Component, we initialized the name state to 'Steve Marley' by setting this.state to { name: Steve Marley } in the constructor whereas in Functional componentthe only argument to the useState() Hook is the initial state.  Unlike with classes, the state does not have to be an object. We can keep a number or a string if that is all we need. What does useState return?It returns two variables in the array [name, setName]  where “name” is the state variable and it could be anything, and setName is the function call (can be named anything), which updates the state by providing a new state. If you are not familiar with the above syntax, please read array destructuring in JavaScript. In our example we have declared a state variable called name and set it to Steve Marley. React will remember its current value between re-renders and provide the most recent one to our function. If we want to update the current name, we can call setName. This is a way to “preserve” some values between the function calls so in other words useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React. It is worth noticing that now our component (functional component) looks pretty simple, crisp and it does not have the level of complexity that a class component normally has. Effect Hook So far, we have seen extracting stateful logic with the help of hooks and defining/setting states inside a component. But what about managing the DOM from one component to another? Or fetching the data through an API? Or handling Events? All these operations which are quite familiar to usare effects!  The Effect Hook adds the ability to perform side effects from a functional component. It is a lifecycle Hook that combinescomponentDidMount, componentDidUpdate, and componentWillUnmount in React classes but unified them into a single API. useEffect(() => {  // Do some task here  }); By calling this hook, we are simply telling our component to perform some tasks after render like Data fetching, setting up a subscription, and manually changing the DOM in our React components. Let us understand this with an example: import React, { useState, useEffect } from"react"; exportdefaultfunctionGetData() {  const [myData, setData] =useState([]);  useEffect(() => {  fetch("https://jsonplaceholder.typicode.com/todos/1")  .then(response=>response.json())  .then(myData=>setData(myData));     });  return (                        {myData.map(el=> (                     {el.title}  //Dummy Object                 ))}                           );  }Deeper Explanation: As you saw in the code the argument of useEffect() is a function that handles your actions when something affects your component. Here it's important to know that, by default, on every render and re-render the useEffect hook runs. So, whenever your component state changes or your component receives new props, it will re-render and cause the useEffecthook to run again. We do not want that, correct? So, this means that if hooks run every time a component renders, we want to ensure that a hook runs only once when the component gets mounted. In our example, if a component fetches data from an API, we do not want this happening every time the component re-renders! Solution!! The useEffect() hook takes a second parameter which is an array that contains the list of things which will cause the useEffect hook to run. When changed, it will trigger the effect hook. The key solution to running an effect only once is to pass in an empty array just like this: useEffect(() => {  console.log('It will run only once');    }, []); Hence the useEffect will run as usual in the first render. But when the component re-renders useEffect will check if there's nothing in the array, it will do nothing and it won't have to run again.       import React, { useState, useEffect } from"react";       exportdefaultfunctionGetData() {  const [myData, setData] =useState([]);  useEffect(() => {  fetch("Some API")  .then(response=>response.json())  .then(data=>setData(data));      }, []);     //Line 11  return (                        {myData.map(el=> (                     {el.name}  //Dummy Object                 ))}                           );  }This array at line 11 contains a list of state variables to tell React if they have changed. We can also remove it for optimization purposes. React will only re-run the side effect if one of the items in this array changes. It is worth noting, that a side effect in React may or may not require clean up!  To know more about Effects and tips on using Effects, please read the official documentation hereBuild Your Own Hooks (Custom Hooks) Now there are some instances where you are using the same logic between different components. How to deal with those? Yeah, the old approach is via Render props or HOC’s. But what if we don’t want to add more components to our tree? Custom Hooks solve this problem! A custom hook is a plain JavaScript function that uses React hooks. As a convention, a custom hook's name is prefixed with the word "use" Let us see an example here where we want to reuse the component logic from one component to another. Here the custom Hook is useDeliveryStatus import React, { useState, useEffect } from 'react';  function useDeliveryStatus(deliveryID) {  const [isDelivered, setIsDelivered] = useState(null);  function handleStatusChange(status) {  setIsDelivered(status.isDelivered);  }  useEffect(() => {  DummyAPI.subscribeToDeliveryStatus(deliveryID, handleStatusChange);  return () => {  DummyAPI.unsubscribeFromDeliveryStatus(deliveryID, handleStatusChange);  };  });  return isDelivered;} Here we have imported the useEffecthook and also made use of the useEffect() function to set the state of our “deliveryId” once the API call is successful, which is pretty neat and concise.  It takes deliveryId as an argument and returns the status of whether our product is delivered. There are many other use-cases where we can use our own Hooks to share some common stateful logic between the components. The purpose of our useDeliveryStatus Hook is to check on the delivery status. This is why it takes deliveryID as an argument, and returns whether this item is delivered:   function useDeliveryStatus(deliveryID) {  const [isDelivered, setIsDelivered] = useState(null);      // ...      return isDelivered;    } Custom Hook means fewer keystrokes and less repetitive code. Let’s see how! Using Our Custom Hook: So far we’ve extracted this logic to a useDeliveryStatus hook, we can just use it like this: function itemsDelivered(props) { constisDelivered = useDeliveryStatus(props.deliveredItem.id);    return (              {props. deliveredItem.name}          );  }Here we saw how we can make use of our custom hook in our separate function that serve a different logic. In theabove exampleit highlights theitem delivered in green color and the non-delivered in red! Custom hooks leverage the power of Reacts Hooks and having said that there has been an explosive growth of custom hooks being used by developers all over the world.They solved our problems in many ways and also help in removing the redundancy in the code. We that we have covered a lot about the main types of Hooks, let us nowunderstand about other types of Hooks. Other Hooks  Oncecan’t really imagine all that React hooks are capable of. Nevertheless, the following will give you a solid understanding of this to help you relate better. Apart from thebasic hooks, there areother more advanced hooks available. Don’t’ worry, you don’t need to learn them all at once and you already have an idea of what they are. These advanced hooks are either variantsof basic Hooks or serve different edge cases which you will discover later. Below is a list of some advanced hooks with the descriptions as per the React Official Documentation:HookDescriptionuserReducer()userReducer() is an additional hook which is just alternative to "useState".  It can accept a constant reducer that accepts state and actions and returns the current state with a dispatched method which tells what actions need to be triggered.useCallback()Returns a memoized callback. We can use it by passing an inline callback and an array of inputs. It will return a memoized version of the callback which only changes if one among the inputs has changed.useMemo()It returns a memoized value. useMemo is used for passing a “create” function and an array of inputs. It will only recompute the memoized value when one among the inputs has changed.useRef()useRef returns a ref object where the current property is initialized to the passed argument (initialValue). The returned object will persist for the complete lifetime of the component.useImperativeHandleuseImperativeHandle is very similar but handles two things in addition. While using ref, it customizes the instance value that is exposed to parent components and allows you to replace the native functions such as focus or bluruseLayoutEffectThis one is very similar to useEffect, but it runs synchronously after React has performed the DOM mutations or the screen is updated. All the updates happening inside useLayoutEffect will happen synchronously before the browser gets its first paint.useDebugValueuseDebugValue is generally used to display a label for some miscellaneous or custom hooks in React-Dev Tools. So, aren't hooks our best shot at solving all kind of problems? You bet! But in order to build a flexible and reusable hook, there are some rules which must be followed: Rules of Using a Hook Hooks must always be called at the top level of our React function and not inside any other scope like loops, conditions, or nested functions. This ensures React that hooks are always called in the same order after every render. Hooks must always be called from React function components or custom React Hooks and, not from regular JavaScript functions.  React team has provided us with a lint rule that helps us to make the best of Hooks(enforce the above-mentioned rules). You can also add the same in your ESLint configuration. ConclusionSo, from multiple points of view, we have covered the power of Hooks and seen how we can use controlled state in our Components without utilizing classes. Furthermore, wehave understood how to reuse a stateful logic with reusable custom Hooks that can help in our future undertakings. Remember to apply rules and take the assistance of ESLint module to uphold rules in your code. Hope you find this article useful. Happy Learning!
Rated 4.0/5 based on 15 customer reviews
6532
Introduction to Hooks in React

Technological change is rapidly impacting our pres... Read More