Search

Top ReactJS Features Which Makes It Best For Development

In the real life we see and use several applications. Each application is built for a specific purpose and has some set of style in designing it. To attract more viewers to a particular application the most basic requirement is a good UI for the application. The UI represents the front-end part of an application. Many applications that we use in the day-to-day life like Google, Facebook, Instagram, Snapchat, LinkedIn etc., contains different UI frameworks written in different technologies.  Different technologies like Angular, Meteor, Node etc. are quite popular for designing front-end applications and require a lot of code. React however, has a great significance among all the front-end technologies available at present because of simplicity, flexibility, responsiveness etc., It makes developers to develop the applications with less code. In general, Developers need to hard code on the tasks while developing the applications. React provides a simple framework which can be used to breakdown the work into components and reuse the code. React – The KingReact is a Java-Script Library. It is an open-source, component-based, lightweight, flexible, and efficient Library used to build front-end applications in the real-world. React was developed by Facebook in 2011 for using on their own app. Later, in 2012, React was deployed on Instagram as well. Since 2013, React has become an open-source library and is now used by everyone. React is used to build dynamic and interactive User Interfaces for mobile applications or websites.  The uniqueness of React is that it is used to create Single Page Applications for accessing the components of the application really fast. These days, React is a popularly used front-end JavaScript library in the real world.  Developers can easily write the code and hard coding is not required with react. It can render and update the state of application automatically when there is code change. In React, a Homepage is built using Components by divide and Merge Policy. During the development phase the components of the home page are divided into small parts and then merged to get the overall view of the page. The main feature of the React is Virtual DOM, where we can observe One-Way Data Binding. The reason behind the usage of React in the real-world applications is that, while building the applications React makes two copies of the Virtual DOM, instead of directly updating DOM. Both the copies are stored and are compared and when a change is triggered React updates the view directly. Some of the top features of React are: - Component-Based Architecture Virtual DOM JSX One-way Data Binding Performance Simplicity, etc.,Component ArchitectureIn the React, everything is treated as Components. It means that the development of a web interface or an application in React, is made with the combination of several components, in which each component has a certain logic written in JavaScript. Since the logic for the component is written in JS instead of templates, we can easily pass rich data through the application and keep the state out of DOM. i.e., Developers can rely on the data across the application without the DOM being affected. The Components in React are used to define the interactions and visuals in the applications. Virtual DOMA virtual DOM object is the representation of a DOM object, which creates the virtual copy of the original DOM object. In React, for every DOM object there would be a corresponding Virtual DOM. This feature of React helps to speed up the application development process and provides flexibility. The algorithm facilitates the replication of a web page or application in Reacts virtual memory, which is a representation of the UI kept in the memory and then synced with the real DOM with the help of a library named ReactDOM. DOM generally represents a tree-like structure. In React, virtual DOM refers to the programming area of the virtual representation of a UI Component stored in memory and then synced with the real DOM Object by a library called ReactDOM. It works on One-way Data Binding mechanism, to quickly render the changes in the virtual DOM than updating the changes in the Original DOM. i.e., whenever the application is modified or updated, the entire UI is rendered again by the virtual DOM, by updating the modified components present in the application. This in turn reduces the cost and time taken for the development of application.Function ComponentsFunctional components are a form of JavaScript functions in React. These functions may or may not receive data as parameters like props, and return the output as JSX code, which is also called as React Element used to render to the DOM tree.  These are like functions which contains lesser code to implement a functionality in the application. These functions are easier to understand, and code is reused whenever required. The primary function of a React component is to display the view and combine it with the code to bring out app behaviour. A functional component is easy to define and we can see an example of it below. The function is defined using a function keyword followed by the name of the function, and in the body of the function we write some logic and return the required content to the application. Syntax of Functional Component function Function_Name(){    // block of code    // block of code   return statement  } Example of Normal Function Declaration function Sample(){   return <p>Hello, Welcome to Upgrad KnowledgeHut</p>  } In React, after defining the function we need to render the particular function component to be displayed on the application and it is done using ReactDOM.render function and is as follows: -  ReactDOM.render(   <Sample />,   document.getElementById('root')  ); The above example is written in a separate JavaScript file by importing the required Libraries into it to get the output of the function on the screen. Index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  function Sample(){   return <p>Hello, Welcome to Upgrad KnowledgeHut</p>  }  ReactDOM.render(   <Sample />,   document.getElementById('root')  ); Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;  }  code {  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  } OutputExample of Arrow Function Declaration We can write the above sample function in a separate style called Arrow Function. In React, this can be created using a data type followed by the name of function. The whole code is represented below: Index.jsimport React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  // const displays the data type  const Sample = () => {   return <h5>Hello, Welcome to Upgrad KnowledgeHut</h5>  }  ReactDOM.render(   <Sample />,   document.getElementById('root')  ); Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;  }  code {    font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  } OutputExample of declaring function using props Here we declare the function by passing the parameter into it. The functional component may or may not take the parameters for function execution and then returns the JSX element (React Element) in return. The code is as follows :- Index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  function Welcome(props){  // props is initialized with name   return <h5>Welcome to , {props.name}</h5>  }  ReactDOM.render(  // Here we are giving the value to the name to be called by the prop  // like name=” ”   <Welcome name="Upgrad KnowledgeHut"/>,   document.getElementById('root')  );Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;  }  code {    font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  } Output:The above are some of the different ways to work on functions and they help developers to write code and integrate it to the application easily. Functions help in code reusability, and it is used to decrease the length of the code to give out the better performance. JSXInstead of learning a new syntax for expressing UI elements, React offers JSX which feels like HTML and yet has the complete power of JavaScript behind it. JSX is like a markup syntax that is very close to HTML, which helps in describing the appearance of the application interface. JSX is a combination of Javascript + XML. This JSX exhibits the syntax just like the HTML and is widely used to create the React Components.  React’s JSX feature is pretty great in that it helps the developers write the code for the building blocks of React UI. The code is easy to write, simple to understand and it is an easy way for developers to build applications. The Hooks APIHooks were introduced from the React latest version 16.8, which was released officially in early February 2019. Hooks were shipped additionally with the API that helps us to use state and other features in the React without writing a class.  Hooks feature set enables developers to add opt-in features to the components they build, which means rewriting of code is not necessary and the changes were readily available for usage from React v16.8 and are Backword-Compatible i.e., it doesn’t contain any Breaking changes.  Hooks are like functions that let you work with the React state and the lifecycle features from the function components directly. The primary idea of using Hooks is that it doesn’t allow a developer to work with Classes, but it provides a smart way of using React in developing applications without Classes. Besides custom hooks can be created for building reusable logic that can be shared across the application.When to use Hooks in the application?  When we initially write a function component and want to add a state to the component, classes were typically used for this purpose. But now it is possible in a much easier way by using a Hook Component which can be used directly inside a function. Hooks allow the developers many benefits like: Code Reusability. Good Code Composition. Sharing code logics using custom hooks. Flexibility in navigating to the components. And with the help of Hooks, developers can use functional components to almost everything they need to do in an application, from rendering UI to also to handle state and the logic. Example of Hooks API with “useState” H4 We use one of the functional component named useState() for setting and retrieving state in react. With the help of Hook, we declare a new state in the react app. App.js import React, { useState } from 'react';   function Sample() {    // Declare a new state variable, which we call as count     const [count, setCount] = useState(0);  return (    <div>     <p>Button clicked {count} times</p>     <button onClick={() => setCount(count + 1)}>    Click me    </button>     </div>    );   }   export default Sample;   index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  import App from './App';  ReactDOM.render(   <App />,   document.getElementById('root')  ); Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;  }   code {    font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  } Output In the above example, useState is the Hook which needs to call inside a function component to add some local state to the application. The useState returns a pair of elements, in which the first element is the current state value/initial value, and the second element is a function which allows us to update it. After that, we will call this function from an event handler. Example of Hooks API using “this.setState” H4 The useState is similar to this.setState in class. The equivalent code without Hooks looks like as below App.js import React, { useState } from 'react';   class Sample extends React.Component {    constructor(props) {    super(props);     this.state = {   count: 0    };   }    render() {    return (    <div>     <p>Button clicked {this.state.count} times</p>     <button onClick={() => this.setState({ count: this.state.count + 1 })}>    Click me    </button>     </div>    );   }   }   export default Sample; index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  import App from './App';  ReactDOM.render(   <App />,   document.getElementById('root')  ); Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;  }  code {    font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  }  Output Example of Hooks API with useEffect H4 The useEffect() in Hook allows us to perform an action in the function components in react. This method doesn’t use the components of lifecycle methods present in class components. The useEffect() function in Hooks are like the componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.  App.js import React, { useState, useEffect } from 'react';   function Sample() {    const [count, setCount] = useState(0);    // Similar to componentDidMount and componentDidUpdate functions     useEffect(() => {   // Updating the document title using the browser API   document.title = `Button clicked ${count} times`;   });     return (    <div>     <p>Button clicked {count} times</p>     <button onClick={() => setCount(count + 1)}>    Click me    </button>     </div>    );   }   export default Sample;   index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  import App from './App';  ReactDOM.render(   <App />,   document.getElementById('root')  ); Index.css body {    margin: 0;    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',      'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',      sans-serif;    -webkit-font-smoothing: antialiased;    -moz-osx-font-smoothing: grayscale;    code {    font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',      monospace;  }Output Example of Hooks API with Custom Hooks H4 Custom Hooks are like the JavaScript functions. This custom Hook uses the word “use” that can call other Hooks. In simple terms, the custom Hook is like a function component and the word “use” is used in the beginning of the function tells that it is binded to Hook rules.  App.js import React, { useState, useEffect } from 'react';      const useDocTitle = title => {    useEffect(() => {    document.title = title;   }, [title])   }      function Sample() {    const [count, setCount] = useState(0);    const riseCount = () => setCount(count + 1);    useDocTitle(`Button clicked ${count} times`);       return (    <div>     <p>Button clicked {count} times</p>     <button onClick={riseCount}>Click me</button>     </div>    )   }   export default Sample; index.js import React from 'react';  import ReactDOM from 'react-dom';  import './index.css';  import App from './App';    ReactDOM.render(   <App />,   document.getElementById('root')  ); Output Easy to LearnInstead of making developers learn a completely new syntax or a language, React leverages a developer's existing knowledge of JavaScript and uses regular language constructs such as functions making it easy to learn. It has a smaller learning curve, easy creation of dynamic applications, tools for debugging in an easy way, and a unidirectional data flow i.e., one-way data binding. A developer just needs to recollect his HTML skills to build the applications and all the remaining CSS styles, Bootstrap functions and even JS functions also will be used in the same html tags easily by importing required libraries. It helps a developer with less code and it is easier to remember. It means rather than writing maximum lines of code to implement a particular functionality, React address the same functionality with the help of functions and components in it.  The EcosystemReact is a JavaScript Library, not a framework. It comprises of a massive ecosystem of developers, allied products such as Redux, React Router, Babel, Styling, and others, making it easy for developers to build robust products. React is an open-source, front-end JavaScript Library used to create dynamic applications. It consists of files which are written in the HTML, CSS and JavaScript.  HTML describes what a UI consists of. Like the Content of the UI i.e., text, videos, images, hyperlinks, tables etc., CSS tells us what a UI looks like, i.e., the Appearance i.e., size, color, shape, layout, typography etc., and JavaScript tells us about the behaviour of the UI, that is the Logic present in it i.e., storage, events, forms, configurations, handling events etc. React helps to update or render the changes made by the user only in that page without depending on the other page. It helps in rendering the elements, Capable of Event Handling, conditional Rendering, accessibility of the code, working with web components, APIs, and some Testing Environments. The react code exhibits high performance, reusability of code and provides an abstract communication between components. Full Stack Awesomeness:Node.js is used to host and run the web servers. It is a runtime environment to handle data communications on the server-side. The developers can execute their react codes in the Nodejs environment using npm modules installed in the application. Npm environment can be installed by installing the NodeJs application from the internet, with the appropriate versions that suits to the user system. And we will get “npm” in that application only. Nodejs is a React framework for building full-stack apps quickly. Though it is not a React feature, its presence amplifies the reason why someone should pick React as the framework of choice. Both - React and Nodejs - are written in JavaScript language and can be executed on both server-side and client-side. Server-Side RenderingReact enables developers to either natively or using Next.js build server render-able apps that facilitate performance, SEO and other benefits. Server-Side rendering is also called as SSR, which can render the JavaScript application on the server rather than in the browser. In react, the server returns an initiation to render the HTML pages and the JS scripts in order to make the page interactive.  In simple terms, server-side rendering is a process in which the server converts into the viewable format before sending them to the browser. The reasons behind usage of SSR mechanism in react is due to these reasons: -  Fast loading of pages. Provides better Search Engine Optimization (SEO) ranking. Facilitates with Great user Experience. A better option for static pages, as the SSR helps in loading the content promptly and efficiently. Battle HardenedReact is actively used not only by Facebook but by thousands of large and small enterprises like Netflix, Dropbox, Instacart, Scribd, Yahoo etc., for their production grade products and is thus battle hardened. Consequently Meta's (formerly Facebook) commitment to React's evolution is outstanding. Due to its simplicity and high performance, React is used in various applications in today’s world. It provides users to write code in an easier way and has one-way data binding mechanism to load the page fast. React helps developers to work on the large applications by rendering the components to the server and getting out a clear view of the page.React for the win! There’s a lot of features that make React a winner; being an open source, efficient front-end framework for developing applications is just one of them. React helps developers to build websites in a dynamic environment. It exhibits higher performance, fast loading of the contents of the page, one-way data binding mechanism, less code, easy integration of APIs, rendering objects to the server etc. It follows a component-based architecture provides divide and merge structure to simplify the whole tasks in the application. It consists of a virtual DOM which can connect with the original DOM object to render the changes made in the application.  In React, everything is like functions or components to implement a particular task in the application. React is the form of JSX code means JavaScript and XML or HTML code used to code for the application. JS implement the logic whereas HTML implements the content of the file. The Hooks API is used to display and render the state without the help of classes. React provides better framework for full stack developers to build the applications. All the activity codes written in react, will be subjected to server-side rendering for a good representational view of the application. It helps in quickly loading the page and indexes the content of the page for exhibiting better SEO ranking. 

Top ReactJS Features Which Makes It Best For Development

6K
Top ReactJS Features Which Makes It Best For Development

In the real life we see and use several applications. Each application is built for a specific purpose and has some set of style in designing it. To attract more viewers to a particular application the most basic requirement is a good UI for the application. The UI represents the front-end part of an application. Many applications that we use in the day-to-day life like Google, Facebook, Instagram, Snapchat, LinkedIn etc., contains different UI frameworks written in different technologies.  

Different technologies like Angular, Meteor, Node etc. are quite popular for designing front-end applications and require a lot of code. React however, has a great significance among all the front-end technologies available at present because of simplicity, flexibility, responsiveness etc., It makes developers to develop the applications with less code. In general, Developers need to hard code on the tasks while developing the applications. React provides a simple framework which can be used to breakdown the work into components and reuse the code. 

React – The King

React is a Java-Script Library. It is an open-source, component-based, lightweight, flexible, and efficient Library used to build front-end applications in the real-world. React was developed by Facebook in 2011 for using on their own app. Later, in 2012, React was deployed on Instagram as well. Since 2013, React has become an open-source library and is now used by everyone. React is used to build dynamic and interactive User Interfaces for mobile applications or websites.  

The uniqueness of React is that it is used to create Single Page Applications for accessing the components of the application really fast. These days, React is a popularly used front-end JavaScript library in the real world.  Developers can easily write the code and hard coding is not required with react. It can render and update the state of application automatically when there is code change. 

In React, a Homepage is built using Components by divide and Merge Policy. During the development phase the components of the home page are divided into small parts and then merged to get the overall view of the page. The main feature of the React is Virtual DOM, where we can observe One-Way Data Binding. The reason behind the usage of React in the real-world applications is that, while building the applications React makes two copies of the Virtual DOM, instead of directly updating DOM. Both the copies are stored and are compared and when a change is triggered React updates the view directly. 

Some of the top features of React are: - 

  • Component-Based Architecture 
  • Virtual DOM 
  • JSX 
  • One-way Data Binding 
  • Performance 
  • Simplicity, etc.,

Component Architecture

In the React, everything is treated as Components. It means that the development of a web interface or an application in React, is made with the combination of several components, in which each component has a certain logic written in JavaScript. 

Since the logic for the component is written in JS instead of templates, we can easily pass rich data through the application and keep the state out of DOM. i.e., Developers can rely on the data across the application without the DOM being affected. The Components in React are used to define the interactions and visuals in the applications. 

Virtual DOM

A virtual DOM object is the representation of a DOM object, which creates the virtual copy of the original DOM object. In React, for every DOM object there would be a corresponding Virtual DOM. This feature of React helps to speed up the application development process and provides flexibility. The algorithm facilitates the replication of a web page or application in Reacts virtual memory, which is a representation of the UI kept in the memory and then synced with the real DOM with the help of a library named ReactDOM. 

DOM generally represents a tree-like structure. In React, virtual DOM refers to the programming area of the virtual representation of a UI Component stored in memory and then synced with the real DOM Object by a library called ReactDOM. 

It works on One-way Data Binding mechanism, to quickly render the changes in the virtual DOM than updating the changes in the Original DOM. i.e., whenever the application is modified or updated, the entire UI is rendered again by the virtual DOM, by updating the modified components present in the application. This in turn reduces the cost and time taken for the development of application.

Function Components

Functional components are a form of JavaScript functions in React. These functions may or may not receive data as parameters like props, and return the output as JSX code, which is also called as React Element used to render to the DOM tree.  

These are like functions which contains lesser code to implement a functionality in the application. These functions are easier to understand, and code is reused whenever required. The primary function of a React component is to display the view and combine it with the code to bring out app behaviour. A functional component is easy to define and we can see an example of it below. 

The function is defined using a function keyword followed by the name of the function, and in the body of the function we write some logic and return the required content to the application. 

Syntax of Functional Component 

function Function_Name(){ 
  // block of code 
  // block of code 
  return statement 
} 
  1. Example of Normal Function Declaration 

function Sample(){ 
  return <p>Hello, Welcome to Upgrad KnowledgeHut</p> 
} 

In React, after defining the function we need to render the particular function component to be displayed on the application and it is done using ReactDOM.render function and is as follows: -  

ReactDOM.render( 
    <Sample />, 
  document.getElementById('root') 
); 

The above example is written in a separate JavaScript file by importing the required Libraries into it to get the output of the function on the screen. 

Index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
function Sample(){ 
  return <p>Hello, Welcome to Upgrad KnowledgeHut</p> 
} 
ReactDOM.render( 
    <Sample />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
} 
code { 
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
} 

OutputTop ReactJS Features Which Makes It Best For Development

  1. Example of Arrow Function Declaration 

We can write the above sample function in a separate style called Arrow Function. In React, this can be created using a data type followed by the name of function. The whole code is represented below: 

Index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
// const displays the data type 
const Sample = () => { 
  return <h5>Hello, Welcome to Upgrad KnowledgeHut</h5> 
} 
ReactDOM.render( 
    <Sample />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
} 
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
} 

Output

Top ReactJS Features Which Makes It Best For Development

  1. Example of declaring function using props 

Here we declare the function by passing the parameter into it. The functional component may or may not take the parameters for function execution and then returns the JSX element (React Element) in return. 

The code is as follows :- 

Index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
function Welcome(props){ 
// props is initialized with name 
  return <h5>Welcome to , {props.name}</h5> 
} 
ReactDOM.render( 
// Here we are giving the value to the name to be called by the prop 
// like name=” ” 
    <Welcome name="Upgrad KnowledgeHut"/>, 
  document.getElementById('root') 
);

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
} 
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
} 

Output:Top ReactJS Features Which Makes It Best For Development

The above are some of the different ways to work on functions and they help developers to write code and integrate it to the application easily. Functions help in code reusability, and it is used to decrease the length of the code to give out the better performance. 

JSX

Instead of learning a new syntax for expressing UI elements, React offers JSX which feels like HTML and yet has the complete power of JavaScript behind it. 
JSX is like a markup syntax that is very close to HTML, which helps in describing the appearance of the application interface. JSX is a combination of Javascript + XML. This JSX exhibits the syntax just like the HTML and is widely used to create the React Components.  

React’s JSX feature is pretty great in that it helps the developers write the code for the building blocks of React UI. The code is easy to write, simple to understand and it is an easy way for developers to build applications. 

The Hooks API

Hooks were introduced from the React latest version 16.8, which was released officially in early February 2019. Hooks were shipped additionally with the API that helps us to use state and other features in the React without writing a class.  

Hooks feature set enables developers to add opt-in features to the components they build, which means rewriting of code is not necessary and the changes were readily available for usage from React v16.8 and are Backword-Compatible i.e., it doesn’t contain any Breaking changes.  

Hooks are like functions that let you work with the React state and the lifecycle features from the function components directly. The primary idea of using Hooks is that it doesn’t allow a developer to work with Classes, but it provides a smart way of using React in developing applications without Classes. Besides custom hooks can be created for building reusable logic that can be shared across the application.

When to use Hooks in the application?  

When we initially write a function component and want to add a state to the component, classes were typically used for this purpose. But now it is possible in a much easier way by using a Hook Component which can be used directly inside a function. 

Hooks allow the developers many benefits like: 

  • Code Reusability. 
  • Good Code Composition. 
  • Sharing code logics using custom hooks. 
  • Flexibility in navigating to the components. 

And with the help of Hooks, developers can use functional components to almost everything they need to do in an application, from rendering UI to also to handle state and the logic. 

  1. Example of Hooks API with “useState” H4 

We use one of the functional component named useState() for setting and retrieving state in react. With the help of Hook, we declare a new state in the react app. 

App.js 

import React, { useState } from 'react';   
function Sample() {   
  // Declare a new state variable, which we call as count   
  const [count, setCount] = useState(0);  
  return (   
    <div>   
      <p>Button clicked {count} times</p>   
      <button onClick={() => setCount(count + 1)}>   
        Click me   
      </button>   
    </div>   
  );   
}   
export default Sample;   

index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import App from './App'; 
ReactDOM.render( 
  <App />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
}  
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
} 

Output 

In the above example, useState is the Hook which needs to call inside a function component to add some local state to the application. The useState returns a pair of elements, in which the first element is the current state value/initial value, and the second element is a function which allows us to update it. After that, we will call this function from an event handler. 

  1. Example of Hooks API using “this.setState” H4 

The useState is similar to this.setState in class. The equivalent code without Hooks looks like as below 

App.js 

import React, { useState } from 'react';   
class Sample extends React.Component {   
  constructor(props) {   
    super(props);   
    this.state = {   
      count: 0   
    };   
  }   
  render() {   
    return (   
      <div>   
        <p>Button clicked {this.state.count} times</p>   
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>   
          Click me   
        </button>   
      </div>   
    );   
  }   
}   
export default Sample; 

index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import App from './App'; 
ReactDOM.render( 
  <App />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
} 
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
}  

Output Top ReactJS Features Which Makes It Best For Development

  1. Example of Hooks API with useEffect H4 

The useEffect() in Hook allows us to perform an action in the function components in react. This method doesn’t use the components of lifecycle methods present in class components. The useEffect() function in Hooks are like the componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.  

App.js 

import React, { useState, useEffect } from 'react';   
function Sample() {   
  const [count, setCount] = useState(0);    
// Similar to componentDidMount and componentDidUpdate functions   
  useEffect(() => {   
    // Updating the document title using the browser API   
    document.title = `Button clicked ${count} times`;   
  });    
  return (   
    <div>   
      <p>Button clicked {count} times</p>   
      <button onClick={() => setCount(count + 1)}>   
        Click me   
      </button>   
    </div>   
  );   
}   
export default Sample;   

index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import App from './App'; 
ReactDOM.render( 
  <App />, 
  document.getElementById('root') 
); 

Index.css 

body { 
  margin: 0; 
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 
    sans-serif; 
  -webkit-font-smoothing: antialiased; 
  -moz-osx-font-smoothing: grayscale; 
 
code { 
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 
    monospace; 
}

Output 

Top ReactJS Features Which Makes It Best For Development

  1. Example of Hooks API with Custom Hooks H4 

Custom Hooks are like the JavaScript functions. This custom Hook uses the word “use” that can call other Hooks. In simple terms, the custom Hook is like a function component and the word “use” is used in the beginning of the function tells that it is binded to Hook rules.  

App.js 

import React, { useState, useEffect } from 'react';   
  
const useDocTitle = title => {   
  useEffect(() => {   
    document.title = title;   
  }, [title])   
}   
  
function Sample() {   
  const [count, setCount] = useState(0);   
  const riseCount = () => setCount(count + 1);   
  useDocTitle(`Button clicked ${count} times`);   
  
  return (   
    <div>   
      <p>Button clicked {count} times</p>   
      <button onClick={riseCount}>Click me</button>   
    </div>   
  )   
}   
export default Sample; 

index.js 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import App from './App'; 
 
ReactDOM.render( 
  <App />, 
  document.getElementById('root') 
); 

Output 

Top ReactJS Features Which Makes It Best For Development

Easy to Learn

Instead of making developers learn a completely new syntax or a language, React leverages a developer's existing knowledge of JavaScript and uses regular language constructs such as functions making it easy to learn. It has a smaller learning curve, easy creation of dynamic applications, tools for debugging in an easy way, and a unidirectional data flow i.e., one-way data binding. 

A developer just needs to recollect his HTML skills to build the applications and all the remaining CSS styles, Bootstrap functions and even JS functions also will be used in the same html tags easily by importing required libraries. It helps a developer with less code and it is easier to remember. It means rather than writing maximum lines of code to implement a particular functionality, React address the same functionality with the help of functions and components in it.  

The Ecosystem

React is a JavaScript Library, not a framework. It comprises of a massive ecosystem of developers, allied products such as Redux, React Router, Babel, Styling, and others, making it easy for developers to build robust products. React is an open-source, front-end JavaScript Library used to create dynamic applications. It consists of files which are written in the HTML, CSS and JavaScript.  

HTML describes what a UI consists of. Like the Content of the UI i.e., text, videos, images, hyperlinks, tables etc., CSS tells us what a UI looks like, i.e., the Appearance i.e., size, color, shape, layout, typography etc., and JavaScript tells us about the behaviour of the UI, that is the Logic present in it i.e., storage, events, forms, configurations, handling events etc. 

React helps to update or render the changes made by the user only in that page without depending on the other page. It helps in rendering the elements, Capable of Event Handling, conditional Rendering, accessibility of the code, working with web components, APIs, and some Testing Environments. The react code exhibits high performance, reusability of code and provides an abstract communication between components. 

Full Stack Awesomeness:

Node.js is used to host and run the web servers. It is a runtime environment to handle data communications on the server-side. The developers can execute their react codes in the Nodejs environment using npm modules installed in the application. Npm environment can be installed by installing the NodeJs application from the internet, with the appropriate versions that suits to the user system. And we will get “npm” in that application only. 

Nodejs is a React framework for building full-stack apps quickly. Though it is not a React feature, its presence amplifies the reason why someone should pick React as the framework of choice. Both - React and Nodejs - are written in JavaScript language and can be executed on both server-side and client-side. 

Server-Side Rendering

React enables developers to either natively or using Next.js build server render-able apps that facilitate performance, SEO and other benefits. Server-Side rendering is also called as SSR, which can render the JavaScript application on the server rather than in the browser. In react, the server returns an initiation to render the HTML pages and the JS scripts in order to make the page interactive.  

In simple terms, server-side rendering is a process in which the server converts into the viewable format before sending them to the browser. The reasons behind usage of SSR mechanism in react is due to these reasons: -  

  • Fast loading of pages. 
  • Provides better Search Engine Optimization (SEO) ranking. 
  • Facilitates with Great user Experience. 
  • A better option for static pages, as the SSR helps in loading the content promptly and efficiently. 

Battle Hardened

React is actively used not only by Facebook but by thousands of large and small enterprises like Netflix, Dropbox, Instacart, Scribd, Yahoo etc., for their production grade products and is thus battle hardened. Consequently Meta's (formerly Facebook) commitment to React's evolution is outstanding. 

Due to its simplicity and high performance, React is used in various applications in today’s world. It provides users to write code in an easier way and has one-way data binding mechanism to load the page fast. React helps developers to work on the large applications by rendering the components to the server and getting out a clear view of the page.

React for the win! 

There’s a lot of features that make React a winner; being an open source, efficient front-end framework for developing applications is just one of them. React helps developers to build websites in a dynamic environment. It exhibits higher performance, fast loading of the contents of the page, one-way data binding mechanism, less code, easy integration of APIs, rendering objects to the server etc. It follows a component-based architecture provides divide and merge structure to simplify the whole tasks in the application. It consists of a virtual DOM which can connect with the original DOM object to render the changes made in the application.  

In React, everything is like functions or components to implement a particular task in the application. React is the form of JSX code means JavaScript and XML or HTML code used to code for the application. JS implement the logic whereas HTML implements the content of the file. The Hooks API is used to display and render the state without the help of classes. React provides better framework for full stack developers to build the applications. All the activity codes written in react, will be subjected to server-side rendering for a good representational view of the application. It helps in quickly loading the page and indexes the content of the page for exhibiting better SEO ranking. 

Harsha

Harsha Vardhan Garlapati

Blog Writer at KnowledgeHut

Harsha Vardhan Garlapati is a Data Science Enthusiast and loves working with data to draw meaningful insights from it and further convert those results and implement them in business growth. He is a final year undergraduate student and passionate about Data Science. He is a smart worker, passionate learner,  an Ice-Breaker and loves to participate in Hackathons to work on real time projects. He is a Toastmaster Member at S.R.K.R Toastmasters Club, a Public Speaker, a good Innovator and problem solver.

Join the Discussion

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

Suggested Blogs

Angular: Add service to module Code Example

What are services in an Angular app?Services is a general term broadly categorized as values, functions, or features that our application may need. Services are made to reuse codes designed for a purpose.Angular services differentiate an element from its service so that the services can be re-used. This increases the modularity of the Angular application. Service in an Angular App can be almost anything, it can be an element, a component, or it can be a module used for some specific purpose.All services in Angular App are classes with a definite purpose. It serves a purpose and serves it well.Some of the very well-known services include:Logging Service: Used for logging in, logging out.Data Fetching: Fetching Data and representing it in a formatted way.Data Service: Fetching and receiving Data.Message Bus: Used for communicating through a set of shared interfaces.Tax Calculator: Calculating Tax by synchronizing with the current Law system.EMI calculator: Easy Monthly Instalment Calculator, mainly used in calculations related to Loan. Application Configuration: Common configuration throughout the application support.ReusabilityReusability is very important when building large-scale applications. Classes built for a common purpose should not be required to be built again and again. This even causes misinterpretation of certain important classes. We need to implement separation of concerns to segregate different classes used for different purposes. This can be achieved by Angular services.In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module.All the Angular Services contain many methods that maintain data throughout the lifetime of an application. Thus, it has become a medium to share various responsibilities within one or multiple components.Services and Dependency InjectionServices provide us with injectable features. The Angular App provides us the decorator @Injectable for creating a service. Classes thereby created can be injected into any other module or component by calling it through service provider modules.The two-step process for creating a service in Angular application is:Use @Injectable decorator to create a class.Use Dependency Injection to inject the class or register the class with the service provider.In Angular 13 Framework, one of the ways of performing DI – Dependency Injection is by using Service injection. Dependencies are services or objects of a class that helps in performing its function. Dependency injection or DI are design patterns in which a class demands dependencies from external sources rather than constructing them.Building and providing servicesLet us build a service for keeping Records of Employees:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it fromhttps://nodejs.org/en/download/The latest Version is : node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website https://cli.angular.io/You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4ServiceSyntax:ng new app_nameC:\>ng new ngApp4Service It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS….Step 4: Generate Service via CLI:Syntax for creating a service:ng generate service [options]ng g service [options]Let us generate the required service: here we are going to create “Employee” Service.Go to the app folder and install the required service: “Employee”:Step 5: Edit the service ts file:Service to store Employee Data: employee.service.tsFile name: employee.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EmployeeService { public _empList: Array = [];       constructor() {           this._empList = [{name:'Jay Choudhury', city:'Ghaziabad'}];       }        returnEmpData(): Array {           return this._empList;       }        addEmpData(item: any): void {           this._empList.push(item);       }   }Step 6: Import the employee service:Import the service in the app.module.ts:import { BrowserModule } from '@angular/platform-browser';   import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';   import { FormsModule, ReactiveFormsModule } from '@angular/forms';   import { AppComponent } from './app.component';   import { EmployeeService } from './employee.service';   @NgModule({     declarations: [       AppComponent     ],     imports: [       BrowserModule, FormsModule, ReactiveFormsModule     ],     providers: [EmployeeService],     bootstrap: [AppComponent],     schemas: [NO_ERRORS_SCHEMA]   })   export class AppModule { }Step 7: Use the service: Employee:Edit: app.component.tsimport { Component, OnInit } from '@angular/core';   import { EmployeeService } from './employee.service';   @Component({       selector: 'app-root',         templateUrl: './app.component.html',         styleUrls : ['./app.component.css']         })   export class AppComponent implements OnInit {         public model: any = {};         public source: Array;         constructor(public service: EmployeeService) {               this.source = this.service.returnEmpData();               }          ngOnInit(): void { }          public submit(): void {               if (this.validate()) {                   this.service.addEmpData(this.model);                   this.reset();               }           }         public reset(): void {          this.model = {};      }          public validate(): boolean {                  let status: boolean = true;                  if (typeof (this.model.name) === "undefined") {                         alert('Name is Blank');                         status = false;                         return status;                        }                  else if (typeof (this.model.city) === "undefined") {                         alert('City is Blank');                         status = false;                         return status;                        }                  return status;           }    }Edit app.component.html:         Employee Form             Employee Name                       City                                           Employee Details                                         Employee's Name                     City                                   {{item.name}}                         {{item.city}}                                     Step 8: Run to check the service:Go to the app folder:C:\>ng serveRun at localhost:http://localhost:4200/We get the Employee Form.We can add more details for the employee, and see the result.Importance of ServicesAngular App provides Angular Services as re-usable components of the application. It uses @Injectable Decorator for building a Service. A service can be called through multiple components as a common element and shared for various purposes. This helps in avoiding repetitive work and improves the speed of app development.
4975
Angular: Add service to module Code Example

What are services in an Angular app?Services is ... Read More

Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!What is GraphQL? A quick primerBefore understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.GraphQL is Client-Driven, whereas REST is Server-Driven.Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.Some of the other advantages of using GraphQL are:GraphQL is faster than other communication APIs.GraphQL can retreat multiple resources and results with a single request.It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.No under and over data fetching. It fetches the amount of data that is required.The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.Let’s Play with GraphQLTo get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.Prerequisites:Understanding of GraphQLNode Package Manager (or NPM) with version 10+Knowledge of basic querying and server-side programming.We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.Setting up Express GraphQLLet’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.$ mkdir graphql-example $ cd graphql-exampleUse NPM to intiialize a project$ npm init -yInstall the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.$ npm install express mongoose body-parser cors --saveApollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.$ npm install apollo-server-express --saveThis should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.const express = require('express'); const mongoose = require('mongoose'); const schema = require('./schema'); const bodyParser = require('body-parser'); const cors = require('cors'); const { ApolloServer } = require('apollo-server-express'); const url = "mongodb://localhost:27017/moviesdb"; const connect = mongoose.connect(url, { useNewUrlParser: true }); connect.then((db) => {       console.log('Connected correctly to server!'); }, (err) => {       console.log(err); }); const server = new ApolloServer({       typeDefs: schema.typeDefs,       resolvers: schema.resolvers }); const app = express(); app.use(bodyParser.json()); app.use('*', cors()); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () =>   console.log(`Server ready at  http://localhost:4000${server.graphqlPath}`));In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.const mongoose = require('mongoose'); const Schema = mongoose.Schema; const movieSchema = new Schema({     name: {        type: String,        required: true     },     rating: {        type: Number,        required: true     },     producer: {        type: String,        required: true    } }, {     timestamps: true }); var Movies = mongoose.model('Movie', movieSchema); module.exports = {Movies, movieSchema};We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.Designing the SchemaLet’s move on to the schema.js file where you’re going to build our GraphQL API.Create a new file in the root of the folder by the name of schema.js and add the following code.const { gql } = require('apollo-server-express');   const Movie = require('./models/movie').Movies;   const typeDefs = gql `    type Movie {      id: ID!      name: String!      producer: String!      rating: Float!  }  type Query {    getMovies: [Movie]    getMovie(id: ID!): Movie  }  type Mutation {      addMovie(name: String!, producer: String!, rating: Float!): Movie      updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie      deleteMovie(id: ID!): Movie    } `In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:const resolvers = {   Query: {     getMovies: (parent, args) => {       return Movie.find({});     },     getMovie: (parent, args) => {       return Movie.findById(args.id);     }   },   Mutation: {     addMovie: (parent, args) => {       let movie = new Movie({         name: args.name,         producer: args.producer,         rating: args.rating,       });       return movie.save();     },     updateMovie: (parent, args) => {       if (!args.id) return;         return Movie.findOneAndUpdate(          {            _id: args.id          },          {            $set: {              name: args.name,              producer: args.producer,              rating: args.rating,            }          }, {new: true}, (err, Movie) => {            if (err) {              console.log('Something went wrong when updating the movie');            } else {              continue;            }          }       );     }   } } module.exports = {typeDefs,resolvers};This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.$ node index.js Server ready at http://localhost:4000/graphqlOnce the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.mutation { addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) { id, name, rating, producer } }OUTPUT:{ “data” : { “addMovie”: { “id”: “5j2j1lnk1LNS231MLK3”, “name”: “GraphQL Movie”, “producer”: “Facebook”, “rating”: 4.5 } } }And now let’s list out all the movies in the database with only their “name” and “rating”.query { getMovies: { name, rating } }OUTPUT:{ “Data”: { “getMovies”: [ { “name”: “GraphQL Movie”, “rating”: 4.5 } ] } }So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.Using GraphQL with ReactUsing GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.Start off by installing the required dependencies.$ npm install create-react-app graphql @apollo/clientCreate a new React appnpx create-react-app movies-appLet’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:import {   ApolloClient,   InMemoryCache,   ApolloProvider,   useQuery,   gql } from "@apollo/client"; const client = new ApolloClient({   uri: 'https://48p1r2roz4.sse.codesandbox.io',   cache: new InMemoryCache() });The URI specifies the GraphQL Server URL.That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.function App() {   return (           My first GraphQL app       ); } render(         ,   document.getElementById('root'), );With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.In the index.js, let’s first define the query you want to execute.const MOVIES = gql`   query getMovies {      name,      producer   } `;Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:function GetMovies() {   const { loading, error, data } = useQuery(MOVIES);   if (loading) return Loading...;   if (error) return Error :(;   return data.map(({ name, producer }) => (                   {name}: Produced by {producer}             )); }Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.Finally, you'll add GetMovies to our existing component tree:function App() {   return (           My first Apollo app             ); }When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.Dev-friendly Query Languages are the FutureSo, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.Keep Learning.
4805
Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the... Read More

How to use Timers in Node.js

You can use Node.js's utilities to schedule the execution of your code. The timer module, unlike most Node.js modules, is not imported. To comply with the JavaScript browser API, the methods are globally accessible.The Node.js Timers module contains several functions that allow you to execute a block of code or a function after a specified amount of time. You don't need to use require() to import the Timers module because it's global.In this post, I'll explain and demonstrate what timers are, how to use them, how the syntax looks, and how you can use them in your applications. For example, if you want to retrieve data from a REST API at a specific interval, you can easily do so with timers. So, even if you are unfamiliar with JavaScript or timers, this post will help you understand these concepts.The Event Loop - A Quick PrimerNode.js is a single-threaded, event-driven platform that can run non-blocking, asynchronous code. These Node.js features make it memory efficient. Even though JavaScript is single-threaded, the event loop enables Node.js to perform non-blocking I/O operations. It is accomplished by delegating tasks to the operating system whenever and wherever possible.Because most operating systems are multi-threaded, they can handle multiple operations that are running in the background. When one of these operations is finished, the kernel notifies Node.js, and the callback associated with that operation is added to the event queue, where it will eventually be executed.Features of Event Loop:An event loop is an infinite loop that waits for tasks, executes them, and then sleeps until more tasks are received.When the call stack is empty, i.e., there are no ongoing tasks, the event loop executes tasks from the event queue.We can use callbacks and promises in the event loop.The event loop executes the tasks in reverse order, beginning with the oldest.Example:console.log("One"); setTimeout(function(){ console.log("Two"); }, 1000); console.log("Three");Output:OneThreeTwoThe first console log statement is pushed to the call stack in the above example, and "One" is logged on the console before the task is popped from the stack. Following that, the setTimeout is added to the queue, the task is sent to the operating system, and the task's timer is set. After that, this task is removed from the stack. The third console log statement is then pushed to the call stack, "Three" is logged on the console, and the task is removed from the stack.Timers in JavaScriptA timer is used in JavaScript to execute a task or function at a specific time. The timer is essentially used to delay the execution of the program or to execute the JavaScript code at regular intervals. You can delay the execution of the code by using a timer. As a result, when an event occurs or a page loads, the code does not complete its execution at the same time.Advertisement banners on websites, which change every 2-3 seconds, are the best example of a timer. These advertising banners are rotated at regular intervals on websites such as Flipkart. To change them, you set a time interval.JavaScript provides two timer functions, setInterval() and setTimeout(), which help to delay code execution and allow one or more operations to be performed repeatedly.setTimeout():The setTimeout() function allows users to postpone the execution of code. The setTimeout() method accepts two parameters, one of which is a user-defined function, and the other is a time parameter to delay execution. The time parameter, which is optional to pass, stores the time in milliseconds (1 second = 1000 milliseconds).setInterval():The setInterval method is similar to the setTimeout() function in some ways. It repeats the specified function after a time interval. Alternatively, you can say that a function is executed repeatedly after a certain amount of time specified by the user in this function.Timers in Node.js - setTimeout()setTimeout() can be used to execute code after a specified number of milliseconds. This function is equivalent to window. setTimeout() from the browser JavaScript API, but no code string can be passed to be executed.setTimeout() takes a function to execute as the first argument and a millisecond delay defined as a number as the second. Additional arguments may be provided, and these will be passed to the function. As an example, consider the following:Using setTimeout()The timeout interval is not guaranteed to execute after that exact number of milliseconds. This is because any other code that blocks or holds onto the event loop will delay the execution of the timeout. The only guarantee is that the timeout will not be executed sooner than the timeout interval specified.setTimeout(function A() { return console.log('Hello World!'); }, 2000); console.log('Executed before A');clearTimeout():The clearTimeout() method deactivates a timer that was previously set with the setTimeout() method.The ID value returned by setTimeout() is passed to the clearTimeout() method as a parameter.Syntax:clearTimeout(id_of_settimeout)Example: function welcome () { console.log("Welcome to Knowledgehut!"); } var id1 = setTimeout(welcome,1000); var id2 = setInterval(welcome,1000); clearTimeout(id1);Timers in Node.js - setImmediate()To execute code at the end of the loop cycle, use the setImmediate() method. In layman's terms, this method divides tasks that take longer to complete, in order to run a callback function that is triggered by other operations such as events.Syntax:let immediateId = setImmediate(callbackFunction, [param1, param2, ...]); let immediateId = setImmediate(callbackFunction);The function to be executed will be the first argument to setImmediate(). When the function is executed, any additional arguments will be passed to it.Now consider the difference between setImmediate() and process. nextTick(), as well as when to use which.While processing, setImmediate() is executed in the Check handlers phase. process.nextTick() is called at the start of the event loop and at the end of each phase.process.nextTick() has higher priority than setImmediate():setImmediate(() => console.log('I run immediately')) process.nextTick(() => console.log('But I run before that'))Output:Using setImmediate()Multiple setImmediate functions are called in the following example. When you do this, the callback functions are queued for execution in the order in which they are created. After each event loop iteration, the entire callback queue is processed. If an immediate timer is queued from within an executing callback, it will not be triggered until the next iteration of the event loop.Example:setImmediate(function A() { setImmediate(function B() { console.log(1); setImmediate(function D() {   console.log(2); }); }); setImmediate(function C() { console.log(3); setImmediate(function E() {   console.log(4); }); }); }); console.log('Started');clearImmediate():The clearImmediate function is used to remove the function call that was scheduled by the setImmediate function. Both of these functions can be found in Node.js's Timers module.Example:console.log("Before the setImmediate call") let timerID = setImmediate(() => {console.log("Hello, World")}); console.log("After the setImmediate call") clearImmediate(timerID);Timers in Node.js - setInterval()This method, unlike setTimeout(), is used to execute code multiple times. For example, the company may send out weekly newsletters to its Edge as a Service customer. This is where the setInterval() method comes into play. It is an infinite loop that will continue to execute as long as it is not terminated (or halted).As the second argument, setInterval() accepts a function argument that will run an infinite number of times with a given millisecond delay. In the same way that setTimeout() accepts additional arguments beyond the delay, these will be passed on to the function call. The delay, like setTimeout(), cannot be guaranteed due to operations that may stay in the event loop and should thus be treated as an approximation.Syntax:let intervalId = setInterval(callbackFunction, [delay, argument1, argument2, ...]); //option 1 let intervalId = setInterval(callbackFunction[, delayDuration]); // option 2 let intervalId = setInterval(code, [delayDuration]); //option 3Using setInterval()Example:setInterval(function A() { return console.log('Hello World!'); }, 1000); // Executed right away console.log('Executed before A');setInterval(), like setTimeout() returns a Timeout object that can be used to reference and modify the interval that was set.In the above example, function A() will execute after every 1000 milliseconds.clearInterval():Example:var si = setInterval(function A() { return console.log("Hello World!"); }, 1000); setTimeout(function() { clearInterval(si); }, 4000);Using Timer.unref()The timer module is used to schedule functions that will be called later. Because it is a global API, there is no need to import (require("timers")) to use it.The Timeout Class contains an object (setTimeout()/setInterval()) that is created internally to schedule actions, and (clearTimeout()/clearInterval()) that can be passed to cancel those scheduled actions. When a timeout is set, the Node.js event loop will continue to run until clearTimeout() is called. The setTimeout() method returns timeout objects that can be used to control this default behaviour, and it exports both the timeout.ref() and timeout.unref() functions.timeout.ref():When the Timeout is active and (timeout.ref()) is called, it requests that the Node.js event loop not exit for an extended period of time. In any case, calling this Method multiple times has no effect.Syntax:timeout.ref()timeout.unref():When the Timeout is enabled, the Node.js event loop is not required to remain active. If any other activity keeps the event loop running, the Timeout object's callback is invoked after the process exits. In any case, calling this Method multiple times has no effect.Syntax:timeout.unref()Example:var Timeout = setTimeout(function alfa() { console.log("0.> Setting Timeout", 12); }); console.log("1 =>", Timeout.ref()); Timeout.unref() Timeout.ref() console.log("2 =>", Timeout.unref()); clearTimeout(Timeout); console.log("3 => Printing after clearing Timeout"); Output:Scheduling Made SimplerIn this tutorial, you learned how to schedule tasks with the Node.js timer module. You've seen how to set timeouts, interval timers for recurring tasks, and how to use set immediate to bypass long operations. You've also seen how to stop these operations using the clear() method for each method.As with learning anything new, practising what you learn will make a big difference to how easily you can perform these tasks. Share your thoughts and questions in the comments as you try out what you’ve learnt.
2239
How to use Timers in Node.js

You can use Node.js's utilities to schedule the ex... Read More