## Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React brought up a new way of writing and thinking about React applications. One of the most popular Hooks among developers so far is useReducer, which allows us to handle some complex state manipulations and updates, and this is what we’ll be learning about in this article.In React there are two main hooks that are used for state management, and we all know them. These are:useState, anduseReducerYou might have heard or used React.useState hook, and if not you can directly read React’s official documentation about Hooks here.Have you ever found any difficulty in choosing a state management library to manage and handle a global state in a React app? Or, what if you need to manage more complicated data structures or perform any side effects?Thinking over these concepts is quite tricky and time-consuming.Well, this is pretty much what we are going to learn and cover in this article, so read on!  PrerequisitesIn order to get the full benefits of this article, I’d recommend you to double check this prerequisite list and set up the environment as suggested.Npm or Yarn installedNode.js version >= 12.x.x installedcreate-react-app cli installed or use npxBasics of React Hooks, (if not kindly read this first)What is a Reducer, anyway?What is the first thing that comes up in your mind when you hear the term reducer in React?For me, I am always reminded of JavaScript's Array.reducer() function.The only job of a reducer is to Reduce!We all know that the original reduce() method in JavaScript executes a given function for each value of an array  considering from left-to-right. And, here React.useReducer in fact, is like a mini Redux reducer.  A reducer is basically a function which determines a change to an application’s state. It takes the help of an action by using it to receive and determine that particular change.In react we have a lot of options, like Redux, that can help to manage the application’s state changes in a single store. Here we will learn about how we can make use of a reducer to manage shared state in an application.Reducer is one of the new custom Hooks introduced in React since v16.8. It allows you to update parts of your component’s state when certain actions are dispatched, and it is very similar to how Redux works.The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().It carries an initial state and a reducer function as its arguments and then provides a state variable and a dispatch function to enable us to update the state. If you’re familiar with how Redux updates the store through reducers and actions, then you already know how useReducer works. And if not, then also we will learn about useReducer functionality in core.So basically, what is useReducer Hook?The useReducer hook is used for complex state manipulations and state transitions.  Just like the other React hooks, we can import useReducer from react as shown in the below snippet:import React, { useReducer } from 'react';React.useReducer is a React hook function that accepts a reducer function, and an initial state.  const [state, dispatch] = useReducer(reducer, initialState);This hook function returns an array with 2 values. The first one is the state value, and the second value is the dispatch function which is further used to trigger an action with the help of array destructuring.  In the context of React, here’s what a typical useReducer pattern looks like:JSX:const reducer = function (currentState, action) { // Make a new state based on the current state and action return newState}const [state, dispatch] = useReducer(reducer, initialValue)// example usage: dispatch({type: "SOMETHING_HAPPENED"}) // Or with an optional "data": dispatch({type: "SOMETHING_HAPPENED", data: newData})Note: The “state” can be of  any kind. It doesn’t have to be an object always. It could be a number, or an array, or anything else.Pretty cool? Now let’s move further and understand how to use useReducer.How to use the useReducer Hook?Earlier we saw the basic useReducer which takes up two arguments: initial state and a reducer function. But useReducer hook actually takes up one more argument including reducer and initial state which is >>> a function to load the initial state lazily.This is usually helpful when we want the initial state to be different depending on some situation and instead of using our actual state, we could create the initial state anywhere, perhaps dynamically, and it will override the initial state.Syntax for the third argument is:const [state, dispatch] = useReducer(reducer, initialArgs, init); Let’s now understand step by step how to use useReducer and understand what’s happening behind the deck.Consider the following classic example of code to see the practical usage of useReducer:// Let’s begin to define the initial state of the component's state const initialState = { count: 0 } // Here is a function will determine how the state is updated function reducer(state, action) {  switch(action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } case 'REPLACE': return { count: action.newCount } case 'RESET': return { count: 0 } default: return state } } // Now inside our component, we can initialize the state like below const [state, dispatch] = useReducer(reducer, initialState);Explanation:In the above code snippet , we have  first defined an initial state for our componentadded a reducer function that updates that state depending on the action dispatched and,we have finally initialized the state for our component.Now as promised earlier, you don’t require an understanding of Redux to understand this concept. So let’s break down everything and see what’s happening.The initialState variableThis is the default value of our component’s state when it gets mounted for the first time inside the application.The reducer functionThe next step is to update the component’s state when some actions occur. This function tells what the state should contain depending on the action. It returns an object, which is then used to replace / change the state.It takes in two arguments which are a state and an action; wherein state is nothing but your application’s current state, and the action is an object which contains the details of all the actions currently happening.An action may typically look like this:const replaceAction = { type: 'REPLACE', newCount: 10, }It usually contains a type: which denotes what type of action it is. An action can also contain more than one data, which can also be the new value to be updated in the state.Dispatching an actionNow after understanding about the reducer and how it determines the next state for our component through actions, let’s see how actions are dispatched.Dispatch is just like a function which we can pass around to other components through props.You must have noticed that useReducer returns two values in an array. The first one is the state object, and the second one is a function called dispatch. This is what is used to dispatch an action.For example, if we want to dispatch replaceAction defined in the above example, we’d do something like this:dispatch(replaceAction) // or dispatch({ type: 'REPLACE', newCount: 10, })Summarising a bit here, hence for using useReducer we need the following:Defining an initial stateProviding a function which contains actions that can update the state.Trigger useReducer to dispatch the updated stateUnderstanding useReducer with examplesLet’s play with some real examples now to understand the concept better:Example:1 Simple Classic Counter ExampleLet’s imagine our Component is Counter. useReducer here in the below code accepts as arguments a reducer function, and an initial state value.  const Counter = () => { const [state, dispatch] = useReducer(reducer, 0)}In this case our state is an integer, which starts from 0:The reducer is a function that takes the current state and an action, which can be a value of any type you want. In this example it’s a string:const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } }We can use JSX to make this simple component work as below:const Counter = () => {const [count, dispatch] = useReducer(reducer, 0) return ( <> Counter: {count} <button onClick={() => dispatch('INCREMENT')}>+</button> <button onClick={() => dispatch('DECREMENT')}>-</button> </> ) } This state can be an object with 'n’ number of properties, but different actions only change one property at a time.Putting up all this together, our Babel will look like:const { useReducer } = React const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } } const Counter = () => { const [count, dispatch] = useReducer(reducer, 0) return ( <> Counter: {count} <button onClick={() => dispatch('INCREMENT')}>+</button> <button onClick={() => dispatch('DECREMENT')}>-</button> </>  ) } ReactDOM.render(<Counter />, document.getElementById('app')) You should get the below output:Example2: Let’s see another TODO example. To show list of items:It was not possible to change the state of an item with the handler function earlier. But however, we can now do so, for example if we need to make the list of items stateful we can do so by using them as initial state for our useReducer hook by defining  reducer function:Consider the following JSX snippet for reducer:import React from 'react'; const initialTodo = [...]; const todoReducer = (state, action) => {  switch (action.type) { case 'DO_TODO':      return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = () => {}; return ( <ul> {todos.map(todo => ( <li key={todo.id}> ... </li> ))} </ul> ); }; export default App; Now we can use the handler to dispatch an action for our reducer function.  Because we need the id as the identifier of a todo item in order to toggle it,  we can pass the item within the handler function by using a encapsulating arrow function as below:const handleChange = todo => { dispatch({ type: 'DO_TODO', id: todo.id }); }; And input will look like:<input type="checkbox" checked={todo.complete} onChange={() => handleChange(todo)} />Let's now implement to check our handler whether a todo item is completed or not by the below condition:const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; Putting up all this together, our component looks like:import React from 'react'; const initialTodo = [ { id: 'a', task: 'Do Something', complete: false,   }, { id: 'b', task: 'Walk over here', complete: false, }, ]; const todoReducer = (state, action) => { switch (action.type) { case 'DO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; return ( <ul> {todos.map(todo => ( <li key={todo.id}> <label> <input type="checkbox" checked={todo.complete} onChange={() => handleChange(todo)} /> {todo.task} </label> </li> ))} </ul> ); }; export default App; And here is the Output:Now the biggest question is:When do we use React.useReducer instead of React.useState? The answer is very simple and I will try to keep it even more simple:We can Use React.useReducer when -----Your application architecture is complex and big in size  When the logic to update state is super complex or you want to update state deep down in your component treeThe state value is either an object or an arrayYou need a more predictable, and maintainable state architecture of the applicationAnd, we can Use React.useState when -----Your application is smallThe state value is a primitive valueSimple UI state transitionsLogic is not complicated and can stay within one componentConclusionThe useReducer hook is a nice addition to the React library which allows for a  simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.It lets you optimize the performance of the components that trigger deep updates because now you can easily pass dispatch down instead of typical callbacks.And even if you take nothing else from this article, you should at least remember this: that useReducer allows us to define how we update our state value.Happy coding!

# Understanding the React useReducer Hook

3K

Introduction

The introduction of Hooks in React brought up a new way of writing and thinking about React applications. One of the most popular Hooks among developers so far is useReducer, which allows us to handle some complex state manipulations and updates, and this is what we’ll be learning about in this article.

In React there are two main hooks that are used for state management, and we all know them. These are:

• useState, and
• useReducer

You might have heard or used React.useState hook, and if not you can directly read React’s official documentation about Hooks here.

Have you ever found any difficulty in choosing a state management library to manage and handle a global state in a React app? Or, what if you need to manage more complicated data structures or perform any side effects?Thinking over these concepts is quite tricky and time-consuming.

Well, this is pretty much what we are going to learn and cover in this article, so read on!

Prerequisites

In order to get the full benefits of this article, I’d recommend you to double check this prerequisite list and set up the environment as suggested.

• Npm or Yarn installed
• Node.js version >= 12.x.x installed
• create-react-app cli installed or use npx
• Basics of React Hooks, (if not kindly read this first)

## What is a Reducer, anyway?

What is the first thing that comes up in your mind when you hear the term reducer in React?

For me, I am always reminded of JavaScript's Array.reducer() function.

The only job of a reducer is to Reduce!

We all know that the original reduce() method in JavaScript executes a given function for each value of an array  considering from left-to-right. And, here React.useReducer in fact, is like a mini Redux reducer.

A reducer is basically a function which determines a change to an application’s state. It takes the help of an action by using it to receive and determine that particular change.

In react we have a lot of options, like Redux, that can help to manage the application’s state changes in a single store. Here we will learn about how we can make use of a reducer to manage shared state in an application.

Reducer is one of the new custom Hooks introduced in React since v16.8. It allows you to update parts of your component’s state when certain actions are dispatched, and it is very similar to how Redux works.

The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().

It carries an initial state and a reducer function as its arguments and then provides a state variable and a dispatch function to enable us to update the state. If you’re familiar with how Redux updates the store through reducers and actions, then you already know how useReducer works. And if not, then also we will learn about useReducer functionality in core.

## So basically, what is useReducer Hook?

The useReducer hook is used for complex state manipulations and state transitions.  Just like the other React hooks, we can import useReducer from react as shown in the below snippet:

import React, { useReducer } from 'react';

React.useReducer is a React hook function that accepts a reducer function, and an initial state.

const [state, dispatch] = useReducer(reducer, initialState);

This hook function returns an array with 2 values. The first one is the state value, and the second value is the dispatch function which is further used to trigger an action with the help of array destructuring.

In the context of React, here’s what a typical useReducer pattern looks like:

JSX:

const reducer = function (currentState, action) { // Make a new state based on the current state and action return newState}const [state, dispatch] = useReducer(reducer, initialValue)// example usage: dispatch({type: "SOMETHING_HAPPENED"}) // Or with an optional "data": dispatch({type: "SOMETHING_HAPPENED", data: newData})

Note: The “state” can be of  any kind. It doesn’t have to be an object always. It could be a number, or an array, or anything else.

Pretty cool? Now let’s move further and understand how to use useReducer.

## How to use the useReducer Hook?

Earlier we saw the basic useReducer which takes up two arguments: initial state and a reducer function. But useReducer hook actually takes up one more argument including reducer and initial state which is >>> a function to load the initial state lazily.

This is usually helpful when we want the initial state to be different depending on some situation and instead of using our actual state, we could create the initial state anywhere, perhaps dynamically, and it will override the initial state.

Syntax for the third argument is:

const [state, dispatch] = useReducer(reducer, initialArgs, init);

Let’s now understand step by step how to use useReducer and understand what’s happening behind the deck.

Consider the following classic example of code to see the practical usage of useReducer:

// Let’s begin to define the initial state of the component's state

const initialState = { count: 0 } // Here is a function will determine how the state is updated

function reducer(state, action) {   switch(action.type) { case 'INCREMENT':  return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } case 'REPLACE': return { count: action.newCount } case 'RESET': return { count: 0 } default: return state } } // Now inside our component, we can initialize the state like below
const [state, dispatch] = useReducer(reducer, initialState);

Explanation:
In the above code snippet , we have

• first defined an initial state for our component
• added a reducer function that updates that state depending on the action dispatched and,
• we have finally initialized the state for our component.

Now as promised earlier, you don’t require an understanding of Redux to understand this concept. So let’s break down everything and see what’s happening.

### The initialState variable

This is the default value of our component’s state when it gets mounted for the first time inside the application.

### The reducer function

The next step is to update the component’s state when some actions occur. This function tells what the state should contain depending on the action. It returns an object, which is then used to replace / change the state.

It takes in two arguments which are a state and an action; wherein state is nothing but your application’s current state, and the action is an object which contains the details of all the actions currently happening.

An action may typically look like this:

const replaceAction = { type: 'REPLACE', newCount: 10, }

It usually contains a type: which denotes what type of action it is. An action can also contain more than one data, which can also be the new value to be updated in the state.

### Dispatching an action

Now after understanding about the reducer and how it determines the next state for our component through actions, let’s see how actions are dispatched.

Dispatch is just like a function which we can pass around to other components through props.

You must have noticed that useReducer returns two values in an array. The first one is the state object, and the second one is a function called dispatch. This is what is used to dispatch an action.

For example, if we want to dispatch replaceAction defined in the above example, we’d do something like this:

dispatch(replaceAction) // or dispatch({ type: 'REPLACE', newCount: 10, })

Summarising a bit here, hence for using useReducer we need the following:

• Defining an initial state
• Providing a function which contains actions that can update the state.
• Trigger useReducer to dispatch the updated state

## Understanding useReducer with examples

Let’s play with some real examples now to understand the concept better:

Example:1 Simple Classic Counter Example

Let’s imagine our Component is Counter. useReducer here in the below code accepts as arguments a reducer function, and an initial state value.

const Counter = () => { const [state, dispatch] = useReducer(reducer, 0)}

In this case our state is an integer, which starts from 0:

The reducer is a function that takes the current state and an action, which can be a value of any type you want. In this example it’s a string:

const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } }

We can use JSX to make this simple component work as below:

const Counter = () => {const [count, dispatch] = useReducer(reducer, 0) return ( <> Counter: {count} <button onClick={() => dispatch('INCREMENT')}>+</button> <button onClick={() => dispatch('DECREMENT')}>-</button> </> ) }

This state can be an object with 'n’ number of properties, but different actions only change one property at a time.

Putting up all this together, our Babel will look like:

const { useReducer } = React const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } } const Counter = () => { const [count, dispatch] = useReducer(reducer, 0) return ( <> Counter: {count} <button onClick={() => dispatch('INCREMENT')}>+</button> <button onClick={() => dispatch('DECREMENT')}>-</button> </>  ) } ReactDOM.render(<Counter />, document.getElementById('app'))

You should get the below output:

Example2: Let’s see another TODO example. To show list of items:

It was not possible to change the state of an item with the handler function earlier. But however, we can now do so, for example if we need to make the list of items stateful we can do so by using them as initial state for our useReducer hook by defining  reducer function:

Consider the following JSX snippet for reducer:

import React from 'react'; const initialTodo = [...]; const todoReducer = (state, action) => {  switch (action.type) { case 'DO_TODO':      return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = () => {}; return ( <ul> {todos.map(todo => ( <li key={todo.id}> ... </li> ))} </ul> ); }; export default App;



Now we can use the handler to dispatch an action for our reducer function.

Because we need the id as the identifier of a todo item in order to toggle it,  we can pass the item within the handler function by using a encapsulating arrow function as below:

const handleChange = todo => { dispatch({ type: 'DO_TODO', id: todo.id }); };

And input will look like:

<input type="checkbox" checked={todo.complete} onChange={() => handleChange(todo)} />

Let's now implement to check our handler whether a todo item is completed or not by the below condition:

const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); };

Putting up all this together, our component looks like:

import React from 'react'; const initialTodo = [ { id: 'a', task: 'Do Something', complete: false,   }, { id: 'b', task: 'Walk over here', complete: false, }, ]; const todoReducer = (state, action) => { switch (action.type) { case 'DO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; return ( <ul> {todos.map(todo => ( <li key={todo.id}> <label> <input type="checkbox" checked={todo.complete} onChange={() => handleChange(todo)} /> {todo.task} </label> </li> ))} </ul> ); }; export default App;

And here is the Output:

Now the biggest question is:

When do we use React.useReducer instead of React.useState? The answer is very simple and I will try to keep it even more simple:

We can Use React.useReducer when -----

• Your application architecture is complex and big in size
• When the logic to update state is super complex or you want to update state deep down in your component tree
• The state value is either an object or an array
• You need a more predictable, and maintainable state architecture of the application

And, we can Use React.useState when -----

• Your application is small
• The state value is a primitive value
• Simple UI state transitions
• Logic is not complicated and can stay within one component

Conclusion

The useReducer hook is a nice addition to the React library which allows for a  simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.

It lets you optimize the performance of the components that trigger deep updates because now you can easily pass dispatch down instead of typical callbacks.

And even if you take nothing else from this article, you should at least remember this: that useReducer allows us to define how we update our state value.

Happy coding!

### KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

## Join the Discussion

Your email address will not be published. Required fields are marked *

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

## Make API Calls the Right Way in Angular

About Angular 10Angular 10 is the latest version of the Angular family. Angular applications are basically designed for Single Page Applications, where all controls are required in single page architecture. Angular is an application based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view to model environment, making it an MVC or MVVM application.Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps which can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the app for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable.IntroductionFront-end applications in today’s programming world use HTTP protocol modules to talk to the back-end services. Almost all current browsers make this communication via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10. The methods of this class have request methods with many types of signatures, and their return types are different based on the signature of the request, thus giving different response types.We will study about HttpClient in detail in the subsequent passage.The Common MistakeOne thing for sure is that we need to call APIs in our programs. If we do so correctly, it can help us in upgrading to further versions, in making test modules, and even in handling errors. One common mistake that programmers usually make is in the call they use API URLs directly in the component. This means that if the API URL is upgraded for any reason, we will need to upgrade the URLs in every single component. For Eg: this.httpClient.get('https://www.userdomain.com/api_name/data/' + this.id);  Again, since we are not validating the path by using the Path variable of Angular, this call might fail if the URL is not valid or not available for some reason. Also, changing the modules with direct call to httpClient will require a lot of changes in the component. Let us now talk about the right approach.The Right WayThe correct approach towards calling APIs in Angular includes the following:Create ConstantsWe need to set global variables in Angular 10 to access our variables synchronously throughout our application. We declare Global variables in a Global Constant file. Create a folder under src/app and name it config. To create the global constant file, name it constants.ts and place it under src/app/config folder.Eg: create the following file: src/app/config/constants.ts Open this file and put global constants like API_ENDPOINT, API_MOCK_ENDPOINT etc. These global variables will be used later in Component files like AppComponent so that they can be used like Site constants. Declaring Global Constants // Angular Modules import { Injectable } from '@angular/core';  @Injectable()  export class Constants { public readonly API_ENDPOINT: string = ' https://www.userdomain.com/';  public readonly API_MOCK_ENDPOINT: string = 'https://www.userdomainmock.com/';  public static TitleOfSite: string = " Making API calls the Right Way by Monica";  }  An example of AppComponent using the above global constant is:  Edit the app.component.ts file from the src/app folder:  src/app/app.component.ts:  import { Component, OnInit } from '@angular/core'; import{ Constants } from './config/constants';  @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: ['./app.component.css']  })  export class AppComponent implements OnInit{      title = Constants.TitleOfSite;      constructor() {          console.log(GlobalConstants.API_ENDPOINT);      }      ngOnInit() {          console.log(this.title);      }  } Run the project by navigating to the project folder and calling ng serve : $cd hello-world$ ng serve  The output will be seen in the browser: https://www.userdomain.com/ Making API calls the Right Way by MonicaCreate a ServiceTo create a service in Angular 10, create a file api-http.service.ts in the src/app/core/services folder. Add the following code in the file as below: // Angular Modules import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ApiHttpService { constructor( // Angular Modules private http: HttpClient ) { } public get(url: string, options?: any) { return this.http.get(url, options); } public post(url: string, data: any, options?: any) { return this.http.post(url, data, options); } public put(url: string, data: any, options?: any) { return this.http.put(url, data, options); } public delete(url: string, options?: any) { return this.http.delete(url, options); } }Use HTTPClient LibraryHttpClient Library is present in @angular/common/http folder. The older version of HttpClient was in @angular/http folder, this is replaced by the upgraded version of the same in @angular/common/http folder.Almost all current browsers communicate with APIs via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.The HttpClient module is built over XMLHttpRequest interface. It wraps all the complexities of this interface and provides extra features like: RxJS Obervables, Interceptors for requests and responses, Typed requests and responses, Error handling techniques, ease in Testing Modules, etc. Benefits of using HTTPClient LibraryHttpClient is a module found in angular/common/http module. HttpClient is based on XMLHttpRequest interface, the Interface which is commonly given by most modern browsers. HttpClient gives us a lot more than XMLHttpRequest, and some of its benefits are:It gives us ease in using testing modules.It has request and response objects in strongly typed manner.It has APIs Support with Observable class object.It provides error handling modules.Importing the libraryIn order to use HttpClient library we need to import HttpClientModule from the @angular/common/http package and include the library in the imports array of the App module : Edit the AppModule file in the src/app folder and add the line on top of the file as follows: src/app/app.module.ts: import { HttpClientModule } from '@angular/common/http'; Configure HTTPClientIncluding HttpClient: Once done, include HttpClientModule in the imports array of the app.module and further use it:import { NgModule }         from '@angular/core'; import { BrowserModule }    from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({   imports: [     BrowserModule,     // import HttpClientModule after BrowserModule.     HttpClientModule,   ],   declarations: [     AppComponent,   ],   bootstrap: [ AppComponent ] }) export class AppModule {} …Now we are ready to use the HttpClient library to send HTTP requests or receive API response. Injecting HttpClient into our Application: Once we have  imported HttpClientModule into the AppModule, we can inject the HttpClient into our application as:import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService {   constructor(private http: HttpClient) { } }Create a query parameterGetting JSON dataIn this example we will request JSON data from the API server. Here our app needs a configuration file on the server, config.json, that specifies resource URLs.{   "demoUrl": "api/demo",   "filename": "assets/demotextfile.txt" } The ConfigService fetches this file with a get() method from HttpClient library as follows: configUrl = 'assets/config.json'; getConfig() {   return this.http.get(this.configUrl); }A component, such as ConfigComponent, injects the ConfigService and this getConfig service method is called from the component as for example:showConfig() {   this.configService.getConfig()     .subscribe((data: Config) => this.config = {         demoUrl: data['demoUrl'],         filename:  data['filename']     }); }The service method returns an Observable object of configuration data. Thus the component subscribes to the method's return value. The subscription callback copies the data fields into the component's config object, which binds the data in the component template for display.We can get the Observable object of typed HTtpResponse from the HttpClient as follows:getConfigResponse(): Observable {   return this.http.get(     this.configUrl, { observe: 'response' }); }Here, HttpClient.get() returns an Observable object of typed HttpResponse rather than just the JSON data.The showConfigResponse() method of the component displays the response headers as well as the configuration.Create Error HandlerHttpClient returns an error object instead of a successful response if a request fails on the server. This usually happens due to a request fail, poor network connection or other network related issues.We can create an error handler component by adding a second callback to the.subscribe():showConfig() {   this.configService.getConfig()     .subscribe(       (data: Config) => this.config = { ...data }, // success path       error => this.error = error // error path     ); }We can give different reasons and feedback for a failed request, but displaying the error object can also help at times. @angular/common/http@angular/common/http implements an HTTP client API for Angular apps that relies on the XMLHttpRequest interface exposed by browsers.This includes testability features, typed request and response objects, request and response interception, observable APIs, and streamlined error handling.Entry point exportsNgModulesHttpClientJsonpModuleConfigures the dependency injector for HttpClient with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected.HttpClientModuleConfigures the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.HttpClientXsrfModuleConfigures XSRF protection support for outgoing requests.ClassesHttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.HttpClientPerforms HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).HttpErrorResponseA response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.HttpHandlerTransforms an HttpRequest into a stream of HttpEvents, one of which will likely be a HttpResponse.HttpHeaderResponseA partial HTTP response which only includes the status and header data, but no response body.HttpHeadersRepresents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed.HttpParamsAn HTTP request/response body that represents serialized parameters, per the MIME type application/x-www-form-urlencoded.HttpRequestAn outgoing HTTP request with an optional typed body.HttpResponseA full HTTP response, including a typed response body (which may be null if one was not returned).HttpResponseBaseBase class for both HttpResponse and HttpHeaderResponse.HttpUrlEncodingCodecProvides encoding and decoding of URL parameter and query-string values.HttpXhrBackendUses XMLHttpRequest to send requests to a backend server.HttpXsrfTokenExtractorRetrieves the current XSRF token to use with the next outgoing request.JsonpClientBackendProcesses an HttpRequest with the JSONP method, by performing JSONP style requests.JsonpInterceptorIdentifies requests with the method JSONP and shifts them to the JsonpClientBackend.XhrFactoryA wrapper around the XMLHttpRequest constructor.StructuresHttpDownloadProgressEventA download progress event.HttpEventTypeType enumeration for the different kinds of HttpEvent.HttpInterceptorIntercepts and handles an HttpRequest or HttpResponse.HttpParameterCodecA codec for encoding and decoding parameters in URLs.HttpProgressEventBase interface for progress events.HttpSentEventAn event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.HttpUploadProgressEventAn upload progress event.HttpUserEventA user-defined event.TypesHTTP_INTERCEPTORSA multi-provider token that represents the array of registered HttpInterceptor objects.HttpEventUnion type for all possible events on the response stream.HttpClient vs HttpBackendHttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.Interceptors sit between the HttpClient interface and the HttpBackend.When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain.abstract class HttpBackend implements HttpHandler {   abstract handle(req: HttpRequest): Observable }HttpClientPerforms HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).Note that the responseType options value is a String that identifies the single data type of the response. A single overload version of the method handles each response type. The value of responseType cannot be a union, as the combined signature could imply.class HttpClient { request(first: string | HttpRequest, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   jsonp(url: string, callbackParam: string): Observable   options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable }The request that we send by HttpClient always go through interceptor of Angular application and the request we send by HttpBackend will dispatch requests directly to the backend, without going through the interceptor chain. So we should use both HttpClient and HttpBackend to send a request.Citation: https://angular.io/api/common/httpConclusionThe above article included all the information that we need for working with APIs for Angular Applications. We worked with the Http module and HttpClient Module. We worked with services and efficient API Calls. We understood how to improve on calling API from an Angular Application.
3393
Make API Calls the Right Way in Angular

About Angular 10Angular 10 is the latest version o... Read More

## Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to install React.js on Windows.React.js is a library which helps us to build and create front end interfaces for Single page applications and it utilises the power of virtual DOM.React.js was an inhouse project of Facebook, and it was made open to the public in the year 2013. The adoption of React.js has seen an upward curve since its avantages have been realized. Various startups and established organizations are now adopting the technology and upgrading their technology stack.1. Prerequisite for WindowsTo install React on Windows, your system will require the minimum configuration as below:Windows XP, Windows 7 (32/64 bit) or higherMinimum 4 GB RAM and higher10 GB available space on the hard diskAt least one Internet Browser e.g. Chrome, Firefox, Microsoft Edge etc.Node.jsActive internet connection minimum speed 512kbps and above.At least one installed code Editor to test and debug your code e.g.  Atom https://atom.io/Sublime https://www.sublimetext.com/Visual studio code https://code.visualstudio.com/download.2. Introduction to React.jsReact.js is a library written in TypeScript. It utilises the syntax of the modern version of JavaScript as described by ES6 and its higher version.Applications built using React.js use the Single reusability principle. This advocates the idea of building web pages and applications using components and unidirectional flow. In React.js we have the concept of states and the concept of immutability. Components have hierarchy in terms of Parent and Child components. A component in case of React.js can be thought of as a piece of code which is based on the principle of pure functions. We will look into the pure component later. First, let’s understand what a state is. For e.g. To become a member of a service, the user fills his information on the registration page. While filling the details there can be many states of the form, for e.g. When the form field is empty or when the form field has witnessed some error on some particular field, which needs to be corrected; or when after correction, the form data has been validated and is ready for submission. So, at a broad level, the registration form has been through various states. These states represent at which level the application is, in terms of interacting with the end-user. Each level of interaction for this form is represented by the state, from an empty form to being a fully filled form with a display of an error for certain fields and the validated form. In React.js, we have the component based on the pure function. A pure function can be memorised as a piece of code, which does one task and does it pretty well. For a certain input, it always returns the same output, so this means we are increasing predictability of the code. Since React.js follows a certain code pattern and principles in order to work, it lowers the curve of the knowledge gap; whether you are one-person or a team of developers working mutually.3. Introduction to Node.js and NPM on WindowsTo run React.js we will require Node.js on our system.Node.js is a server which will help us to run the React.js code.It is based on non-blocking input and output and the Chrome V8 JavaScript engine. The Node.js code is open source.NPM which is an abbreviation of Node package manager, npmjs.com is supported by various developers around the world. It has various node modules, using which developers can host and publish their modules on the open-source community.  It hosts modules in private and public visibility.A module carries code which exists to serve high or low level functionalities. In terms of code adoption and availability of various modules it gives an edge and tries to make the developer more productive.  We can plug in and plug out the module. Some modules are dependent on other modules; which is defined as dependency among modules.While building an application, a developer can pick the module, tweak and remix it to suit the application needs, and can then release to the open-source community. So, instead of reinventing the wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and giving it back to the open source community.4. Download and Install Node.jsTo install Node.js we need to go to the URL https://nodejs.orgDepending upon our Windows OS version in terms of 32 Bit or 64 Bit, we can pick the installer and install that version.  In this tutorial I am using Windows 8, 64 Bit.  The Node.js installer includes NPM. It is best to install the even numbered version of NPM.Depending upon your operating system, the Nodejs.org home page will show the Download button and recommended LTS version.After the download is complete we will go to the downloads folder and run the installer.The installer will show the below Setup Wizard. Click next.The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom right to provide your consent and click on Next to proceed with the installation.The installer will ask for Destination folder and the default path set by installation is C:\Program Files\nodejs\Click on Next buttonThe above screen is an important step in the installation process. And if you see closely it also sets the environmental path variables to command prompt on Windows.Click on Next to continue with the installation.The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.During the installation, if you have allowed for Chocolatey and required modules installation for C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the window.If you are interested in installing it, press Enter to continue.Once the istallation is complete you need to verify the Node.js installation.  For this we will use the command prompt.To run command promptPress keys Win+RAnd type cmd in the window below.Next Click on Ok or Press Enter on the keyboard.5. Installation of ReactAfter installation of Node.js we need to install React.To check the Node.js version, open the Windows command prompt. Press Win+R and type cmd. In the command line, type   node -v to see its version. We can also check for npm version, which is installed with Node.js, with the following command npm -v After running these commands, we can check the node version v14.15.1 and npm version 6.14.8As we have confirmed the Node.js installation we can proceed to the next steps.While in the command prompt, we have navigated to a folder called Codefactory by following the command cd CodefactoryIn this folder we have created a folder  called react-windows by using the command mkdir react-windows.After the folder react-windows has been created, we will change the directory to react-windows with the command cd react-windows React.js can be installed in various ways. Now, we will type npm init. It will ask for the below configuration line by line. Insert your input, followed by Enter keypress to proceed with the next configuration.   At the end of the configuration it will confirm for the inputs you have entered. If you are happy with the configuration data, type yes and enter to continue.The npm init will help us to create a package.json file.Now, the next step to install React.js requires us to go to the command prompt and type the following command in the react-windows directory.npm install --save reactAnd after the above command npm install --save react-domBehind the scene, these commands fetch the specified module from npmjs.com and download it in the local codebase.Let's have a look at the react-windows folder. Here we can see some newly created directories in node_modules.So, in this tutorial, we have learned to install React and reactDOM. But to see the React.js SPA (single page app) there is more work to be done in the above code.As an alternative and fast approach we can do it via create-react-appLet us move to Codefactory folder and with the command cd.. create another folder react-cliNext, type the following command mkdir react-cliNow we will use create-react-app module and type the following commandPlease note that my-fast-app is the name of your app. This is an example and you can be creative in choosing your own name.npx create-react-app my-fast-appIf we see closely it will take care of the rest of the installation steps, and react, react-dom and other related modules are installed automatically.This process is a little data intensive, so please be patient while the download and installation happensWhen the above step gets completed the command prompt displays the below output.Now, let us run our first react app, by navigating to my-fast-app directory as belowcd my-fast-appAnd enter the next command as npm startThe npm command will show the application in the browser. http://localhost:3000And if you are running node.js for the first time using npm command, it will ask for permission to allow access and we need to allow access to run.As we are using a code editor we can have a look at the directory structure and some of the important files, such as index.html in the public folder, in src folder the index.js and App.js. The src folder contains the react component which we can build further on this codebase. index.js is the js invocation point for react app.This index.js is linked with the App.js, which is responsible for showing the content in the browser. That’s what we see on the demo page.Let’s edit the App.js by going to line 10 and adding the following codeTalk is cheap, show me the CodeOnce you save the file by Ctrl+SThe code will be auto refreshed in the browser, after compiling.It will show us the following output.So, now feel free to change messages and alter the page layout and structure for  experimentation.If you are familiar with CSS, you may also change the page style using App.css and tinker with the code as well.SummaryIn this tutorial, we have introduced you to React.js . Its impact in terms of building modern front end interfaces using component-based architecture is significant. We have also touched upon the concept of states, immutability and pure functions.We have got a brief introduction to the Node.js server and NPM modules, the capabilities of Node.js server and the power of the open source community in the npmjs.com.To install React, Node.js installation is a prerequisite.There are various methods for installation. Once we have installed Node.js, React can be installed either by npm commands or by using the create-react-app module.
4508
Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to... Read More

## Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
3496
Installation of React on Mac

Hello learners! In this tutorial we are going to l... Read More