Skillzam

React - JavaScript Library

ReactJS JavaScript Library Home

  • ReactJS (also known as React or react.js) is a free and open-source JavaScript library popular for building user interfaces based on components.
  • ReactJS is often used for developing single-page web applications (SPA) and mobile applications.
  • ReactJS allows developers to create reusable UI components like as in Chakra UI and to manage the state of their application more efficiently, which can result in faster and more efficient rendering of the UI.
     (Chakra UI is a comprehensive library of accessible, reusable, and composable React components that streamlines the development of modern web applications and websites.)
  • React uses a declarative syntax, which means that developers can describe how the UI should look and behave, and React takes care of updating the UI when changes occur. This makes it easier to write and maintain complex UIs.
  • React also supports server-side rendering with frameworks like Next.js, which means that developers can render the UI on the server and send the HTML to the browser, improving the performance and SEO of the application.
  • create-react-app is a development environment that helps to speed up the development process by letting developers focus on their code instead of configuring build tools. create-react-app includes built tools such as webpack, Babel, and ESLint.
  • React has a large and active community, which has created many libraries, tools, and frameworks that can be used with React to make development faster and easier.
  • History of ReactJS:

  • React was created by Jordan Walke, a software engineer at Meta, who released an early prototype of React called "FaxJS".
  • ReactJS was created by Meta (formerly Facebook) and was first released in May 29, 2013.
  • ReactJS was initially developed to solve some of the challenges that Facebook was facing with its web applications, particularly in terms of performance and scalability.
  • The initial version of React focused on the idea of components, which are small, reusable building blocks that can be combined to create complex user interfaces. The use of components allowed developers to create UIs that were easier to maintain and update, and that could be reused across different applications.
  • React Native, which enables native Android, iOS, and UWP development with React, was announced at Facebook's React Conf in February 2015.
  • In March 2015, React was open-sourced and made available to the wider developer community. This led to a rapid increase in popularity, as developers discovered the benefits of using React for building modern web applications.
  • Over the years, React has continued to evolve and improve, with the development of features like the virtual DOM, server-side rendering, and hooks for managing state.
  • On March 29, 2022, React 18 was released which introduced a new concurrent renderer, automatic batching and support for server side rendering with Suspense.
  • Today, React is one of the most popular front-end development frameworks, with a large and active community of developers and companies using it to build modern web applications.
  • Stack Overflow questions asked

    react stact owerflow popular

    Declarative & Imperative Programming

    Difference between Declarative & Imperative Programming
    Declarative Programming Imperative Programming
    Approach Defines what the output should be based on state and props Defines how the output should be created step by step
    Implementation Typically uses React components and JSX to describe the UI Typically uses imperative programming constructs like loops and conditionals to build the UI
    Control Flow Control flow is determined by React's rendering mechanism Control flow is determined by the programmer's code
    Ease of Development Generally easier to read, reason about, and test Can be more difficult to read and reason about
    Efficiency Generally more efficient because React can optimize updates to the UI Can be less efficient because the programmer needs to manually manage updates to the UI
    Examples React component tree, JSX DOM manipulation, jQuery

    Features of ReactJS

    ReactJS is a powerful and flexible library for building user interfaces. Here are some of its key features:

  • Declarative programming: React uses a declarative approach to building UI components, which means that developers can describe the UI they want to create, and React takes care of updating the DOM when changes occur.
  • Component-based architecture: React components are reusable and can be composed together to create complex UIs. Each component has its own state and can communicate with other components through props.
  • Virtual DOM: React uses a virtual DOM, which is a lightweight representation of the actual DOM. This makes it faster to update the UI because React only updates the parts of the DOM that have changed.
  • JSX: JSX is a syntax extension for JavaScript that allows developers to write HTML-like code in their JavaScript files. This makes it easier to create UI components and improves the readability of the code.
  • Unidirectional data flow: React follows a unidirectional data flow, which means that data flows down from parent components to child components. This makes it easier to manage the state of the application and reduces the risk of bugs caused by conflicting data.
  • Server-side rendering: React supports server-side rendering, which means that developers can render the UI on the server and send the HTML to the browser. This improves the performance and SEO of the application.
  • Large and active community: React has a large and active community of developers, which has created many libraries, tools, and frameworks that can be used with React to make development faster and easier.
  • ReactJS in MERN full stack

  • ReactJS is often used in MERN (MongoDB, Express, React, Node.js) full stack development, which is a popular stack for building web applications.
    Here's how React fits into the MERN stack:
    1. 1. MongoDB: is a popular NoSQL database that can be used with Node.js. Developers can use MongoDB to store data for their web application.
    2. 2. Express: is a framework for building web applications with Node.js. Developers can use Express to create a server-side API for their web application.
    3. 3. React: is used to build the client-side of the web application. Developers can use React to create reusable UI components that can be composed together to create complex UIs.
    4. 4. Node.js: is a JavaScript runtime that allows developers to run JavaScript code on the server-side. Developers can use Node.js with Express to create a server-side API for their web application.

  • In MERN full stack development, React is used to create the client-side of the web application, while MongoDB and Node.js with Express are used to create the server-side of the web application.
  • The server-side API can then communicate with the client-side React application to provide data and update the UI in response to user interactions.
  • Overall, the MERN stack provides a powerful and flexible platform for building web applications, with React playing a key role in creating the user interface.
  • Stack Overflow Survey: Web Technologies popularity

    42.62 % of Professional Developers and those learning to code with ReactJS, have done extensive development work in over the past year, and would want to work in over the next year as well.

    Stack Overflow Survey Web Technologies popularity

    Difference between React & Angular

    It's worth noting that both ReactJS and Angular are powerful and widely used library/frameworks for building modern web applications, and the choice between them may depend on the specific needs and preferences of a given project or development team.

    ReactJS vs Angular
    Feature ReactJS Angular
    Language JavaScript TypeScript
    Architecture Component-based Component-based
    State management Flux or Redux RxJS and NgRx
    Templating JSX or other templating libraries Angular Templates
    Learning curve Easy to learn Steep learning curve
    Data binding One-way data binding with props Two-way data binding with ngModel
    Size of library Smaller library Larger library
    Community support Large community support Large community support
    Performance High performance with virtual DOM High performance with change detection
    Development environment Can be used with any text editor or IDE Requires the Angular CLI and specific IDEs
    Mobile development Can be used with React Native Can be used with Ionic, NativeScript, or others
    Testing tools Jest, Enzyme, and others Jasmine, Karma, and others

    Comparision of Github stars

    Comparision of Github stars

    Comparision of Stack Overflow questions asked

    Comparision of Stack Overflow questions asked

    How does ReactJS Work?

    Virtual DOM & Real DOM

    Before understanding how React works, let us see the comparision between Real DOM and Virtual DOM.

    ReactJS Virtual DOM
    Difference between Virtual DOM & Real DOM
    Virtual DOM Real DOM
    Definition A lightweight & in-memory representation of the actual DOM Actual HTML document rendered in the browser, as a tree structure wherein each node is an object represents a part of the document.
    Creation Created and maintained by ReactJS in memory Created and managed by the browser
    Updating ReactJS updates the Virtual DOM when state or props change, and then efficiently applies only the necessary changes to the Real DOM Changes to entire Real DOM are immediately reflected in the browser, which can be slow and inefficient
    Performance More efficient, because React can perform updates to the Virtual DOM without touching the Real DOM Less efficient, because changes to the Real DOM can be slow and require a full page refresh
    Manipulation Can be manipulated directly using JavaScript, but changes will not be reflected in the browser until React updates the Real DOM Can be manipulated directly using JavaScript, with changes immediately reflected in the browser
    Code Sample React.createElement(), setState(), render() document.createElement(), document.getElementById(), innerHTML

    Working of React

    React is a JavaScript library for building user interfaces. React works by using a component-based architecture to build reusable UI components that are rendered to a virtual DOM. When a component's state or props change, React updates the virtual DOM and performs a diffing algorithm to identify the necessary changes to update the actual DOM efficiently. React uses a synthetic event system for event handling and allows state management through the setState() method.

    Here are the basic steps involved in how React works:

    1. 1. Component rendering: React is based on a component-based architecture, which means that the user interface is built by assembling individual components. Each component is responsible for rendering a part of the user interface. When a component is first mounted, React calls its render() method, which returns a React element, a lightweight description of what to render.
    2. ReactJS Components
    3. 2. Virtual DOM: Instead of updating the actual DOM directly, React uses a virtual DOM, an in-memory representation of the actual DOM. When a component's state or props change, React updates the virtual DOM by creating a new tree of React elements.
    4. 3. Reconciliation: React compares the new tree of React elements with the previous one and identifies the differences. This process is called reconciliation. Once React has identified the differences, it updates only the necessary parts of the actual DOM to reflect the changes.
    5. 4. Event handling: React uses a synthetic event system that wraps the native browser events and provides a consistent interface across different browsers. When an event occurs, React invokes the appropriate event handler that is defined in the component.
    6. 5. State management: React allows you to manage the state of a component using the setState() method. When a component's state changes, React re-renders the component and updates the virtual DOM. This triggers the reconciliation process and updates the actual DOM.
    ReactJS Virtual DOM

    Overall, React works by creating a tree of reusable components, managing the component state and props, updating the virtual DOM, and efficiently updating the actual DOM to reflect the changes.

    React Installation & Environment Setup

  • React has been designed from the start for gradual adoption, and you can use as little or as much React as you need.
  • You can get a taste of React, add some interactivity to a simple HTML page, or start a complex React-powered app.
  • Run React locally

  • To try React locally on your computer and to get an overview of what React is, you can write React code directly in a HTML file.
  • This is the easiest and quickest way start learning React.
  • You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.
  • With a few lines of code and no build tooling, React can be used in a small part of the website.
  • Consider the below mentioned standalone HTML file with React Component.

    
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
        <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
        <title>ReactJS Standalone Example</title>
    </head>
    <body>
        <div id="root"></div>
        
        <script type="text/babel">
    
            function MyApp() {
                return (
                    <>
                        <h1>SKILLZAM</h1>
                        <h2>Acquire, Authenticate, Announce your Skills!</h2>
                    </>
                );
            }
    
            const container = document.getElementById('root');
            const root = ReactDOM.createRoot(container);
            root.render(<MyApp />);
    
        </script>
    
    </body>
    </html>
    

    Step 1: Add a DOM Container to the HTML

  • First, open the HTML page you want to edit.
  • Add an empty <div> tag to mark the spot where you want to display something with React.
  • Give this <div> a unique id HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it.
  • You can place a “container” <div> like this anywhere inside the <body> tag. You may have as many independent DOM containers on one page as you need. They are usually empty — React will replace any existing content inside DOM containers.
  • 
    <div id="root"></div>
    
    

    Step 2: Add the Script Tags

  • Both React (react.development.js) and ReactDOM (react-dom.development.js) are available over a CDN.
  • Add three <script> tags to the HTML file in the tag.
  • First two let us write React code in JavaScript, and the third script of babel.min.js allows us to write code in JSX syntax.
  •  
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
    

    Step 3: Add the Script Tag inside body tag

  • script tag contains the React component called App
  • This function return the JSX code with h1 and h2 tags
  • Next three lines of code after function App, will find the <div>, we added to the HTML in the first step, create a React app with it, and then display h1 & h2 React component inside of it.
  • NOTE: Adding JSX to a project doesn't require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.

    
    function MyApp() {
      return (
          <>
              <h1>SKILLZAM</h1>
              <h2>Acquire, Authenticate, Announce your Skills!</h2>
          </>
      );
    }
    
    const container = document.getElementById('root');
    const root = ReactDOM.createRoot(container);
    root.render(<MyApp />);
    
    

    Setup React Environment

    1. Using Vite


    Vite is a build tool that aims to provide a faster and leaner development experience for modern web projects. It consists of two major parts:

  • A dev server that provides rich feature enhancements over native ES modules, for example extremely fast Hot Module Replacement (HMR).
  • A build command that bundles your code with Rollup, pre-configured to output highly optimized static assets for production.
  • To create a project using Vite you first go into the folder where you host all your projects and then the follow the below mentioned steps :

    1. Step 1: Run npm create vite@latest
    2. 
      C:\Users\Skillzam> npm create vite@latest
      
      
    3. Step 2: Choose a name for the project. That will also be the project's folder name.
    4. Step 3: Choose a framework. Pick “React”.
    5. Step 4: Select a variant : Pick JavaScript or TypeScript
    6. Step 5: Now go in the newly created project folder and Install the dependencies: npm install
    7. Step 6: To start the application: npm run dev


    2. Using Next.js


    Next.js is a full-stack React framework. It's versatile and lets you create React apps of any size—from a mostly static blog to a complex dynamic application. To create a new Next.js project, run in your terminal:

    
    C:\Users\Skillzam> npx create-next-app
    
    

    If you're new to Next.js, check out the Next.js tutorial

    Next.js is maintained by Vercel. You can deploy a Next.js app to any Node.js or serverless hosting, or to your own server.



    3. Using Remix


    Remix is a full-stack React framework with nested routing. It lets you break your app into nested parts that can load data in parallel and refresh in response to the user actions. To create a new Remix project, run:

    
    C:\Users\Skillzam> npx create-remix
    
    

    If you're new to Remix, check out the Remix blog tutorial.

    Remix is maintained by Shopify. You can deploy a Remix app to any Node.js or serverless hosting by using or writing an adapter.



    4. Using Gatsby


    Gatsby is a React framework for fast CMS-backed websites. Its rich plugin ecosystem and its GraphQL data layer simplify integrating content, APIs, and services into one website. To create a new Gatsby project, run:

    
    C:\Users\Skillzam> npx create-gatsby
    
    

    If you're new to Gatsby, check out the Gatsby tutorial.

    Gatsby is maintained by Netlify. You can deploy a fully static Gatsby site to any static hosting. If you opt into using server-only features, make sure your hosting provider supports them for Gatsby.



    5. Using create-react-app


    Here's a step-by-step guide on how to install and set up the environment for ReactJS development on your computer using create-react-app.
    Create React App is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration.

    1. [a]. Install Node.js and npm: ReactJS requires Node.js and its package manager, npm. You can download and install them from the official Node.js website: Node Website Link
    2. [b]. Install create-react-app and create a new React project: create-react-app is a command-line tool that allows you to quickly create a new React project with a preconfigured setup. To install and create a new React project (my-reactapp ), open your terminal or command prompt and enter the following command:
      
      C:\Users\Skillzam> npx create-react-app my-reactapp
      
      

      Replace "my-reactapp" with the name of your app. This will create a new React project with the name "my-app" in the current directory.

    3. [c]. Start the development server: Navigate to your project directory by running the following command:
      
      C:\Users\Skillzam> cd my-reactapp
                        
      

      Then start the development server by running the following command:

      
      C:\Users\Skillzam\my-reactapp> npm start
      
      

      This will start the development server and open your app in the browser at http://localhost:3000

      Your browser will display something like this:

      NOTE: If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.

      reactjs Launch

    React Developer Tools

    These Tools are used to inspect React components, edit props and state, and identify performance problems.

    Browser extension

    To debug websites built with React is to install the React Developer Tools browser extension:

  • Install for Chrome
  • Install for Firefox
  • Install for Edge
  • Now, if you visit a website built with React, you will see the Components and Profiler panels.

    ReactJS Developer Tools

    create-react-app Application structure

    create-react-app gives us everything we need to develop a React application. Its initial file structure looks like this:

    
          my-reactapp
          ├── README.md
          ├── node_modules
          ├── package.json
          ├── package-lock.json
          ├── .gitignore
          ├── public
          │   ├── favicon.ico
          │   ├── index.html
          │   ├── logo192.png
          │   ├── logo512.png
          │   ├── manifest.json
          │   └── robots.txt
          └── src
              ├── App.css
              ├── App.js
              ├── App.test.js
              ├── index.css
              ├── index.js
              ├── logo.svg
              ├── reportWebVitals.js
              └── setupTests.js
    
    

  • node_modules (Folder): Contains all the required dependencies & packages that may be used for building React app. For example - Webpack, Babel, Jest & more.

  • package.json (file): This file contains various metadata that is relevant to project. It specifies the dependencies being used in the project which helps npm setup same environment on different machine for our project.
  • package-lock.json (file): is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. Describes exact tree that was generated, such that subsequent installs are able to generate identical trees.
  • .gitignore (file): This file specifies intentionally untracked files that Git should ignore.

  • public (folder): Root folder that gets served up as React app.
    • favicon.ico (file): icon file that is used in index.html as favicon.
    • index.html (file): It is the template file which is served up when we run start script to launch our app. Use this file and inject react components in root div container.
    • logo192.png & logo512.png (files): are react logo images
    • manifest.json (file): to define app, mostly contains metadata.
    • robots.txt (file): Defines rules for spiders, crawlers and scrapers for accessing your app.

  • src (folder): Its a React app folder i.e. containing components, tests, css files etc. It's the mind of React app.
    • App.js (file): This file has very basic react component defined which can be replaced by our own root component
    • App.test.js (file): A basic test(for default app) is defined in this file which can be replace by our own tests. [make use of Jest]
    • index.css (file): Contains styles for general setup of our app.
    • index.js (file): This files renders component and registers service workers(unregistered by default)
    • logo.svg (file): Svg file of React logo, used in component (App.js)
    • reportWebVitals (file): measure performance of React app by passing a function to log results. e.g. reportWebVitals(console.log)
    • setupTests.js (file): This file setups tests & runs them. Directly invoked when tests run from cli ( npm run test ).
  • Things to remember: File Structure of React Applications

  • For the project to build, these files must exist with exact filenames:
    • public/index.html is the page template
    • src/index.js is the JavaScript entry point.
  • You can delete or rename the other files.
  • You may create subdirectories inside src.
  • For faster rebuilds, only files inside src are processed by webpack. Need to put any JS and CSS files inside src, otherwise webpack won't see.
  • ReactJS "Hello World"

    Step 1: Modify App.js file in src folder

  • Inside the src folder, there is a file called App.js. This contains React function component called "App"
  • Make the Changes, as per the below code.
  • NOTE: Remove the import statements, & we do not need logo.svg and App.css

    
    /* "App" component that displays a message */
    
    function App() {
      return (
        <div className="App"> 
          <h1>Hello World!</h1> 
        </div>
      );
    }
    
    export default App;
    
    

    Step 2: Modify index.js file in src folder

  • Inside the src folder, there is a file called index.js
  • Make the Changes, as per the below code.
  • NOTE: Remove the other import statements, & we do not need index.css and reportWebVitals

    
    /* React is rendered to a root element in the HTML page */
    
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    
    
    OUTPUT
    ReactJS Hello World

    Introduction to JSX

    JSX stands for JavaScript Syntax Extension and occasionally referred as JavaScript XML, is an extension to the JavaScript language syntax, which provides a way to structure component rendering using syntax familiar to many developers commonly used in React. It is similar in appearance to HTML.

    JSX lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.

  • JSX allows to write HTML tags inside the JavaScript code
  • Its is easier to write and add HTML in React, than place them in the DOM without any createElement() and/or appendChild() methods
  • JSX converts HTML tags into react elements
  • It is NOT mandatory to use JSX in React
  • JSX is an extension of JavaScript based on ES6, & is translated into regular JavaScript at runtime
  • JSX is created by Meta (formerly Facebook).
  • Why JSX?

  • React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
  • Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both.
  • React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code.
  • JSX also allows React to show more useful error and warning messages.
  • Features of JSX

    1. 1. Write HTML on multiple lines, put the HTML inside parentheses.
    2. In the JSX Example below, the return statement contains the HTML code wrapped inside parentheses:

      
      const Menu = () => {
        return (
          <div>
            <p>Services</p>
            <p>Industry</p>
            <p>About</p>
            <p>Contact</p>
          </div>
        ); 
      }
      
      

    3. 2. HTML code must be wrapped in one top level element, else JSX will throw an error, if the HTML is not correct, or if the HTML misses a parent element.
    4. In the JSX Example above, the <div> element is the top level element that wraps the all the HTML code.


    5. 3. Use a "fragment" to wrap multiple lines. A fragment looks like an empty HTML tag: <> </>
    6. In the JSX Example below, the fragments <> and </> wrap multiple lines:

      
      function App() {
        return (
          <>
            <ul>Shopping List: 
              <li>Tea</li>
              <li>Coffee</li>
              <li>Sugar</li>
              <li>Milk</li>
            </ul>
          </>
        ); 
      }
      
      

    7. 4. Use of curly braces { }
      • JSX uses urly braces { } to write expressions
      • Valid things you can have in a JSX Expression:
        • A string like "skillzam"
        • A number like 99
        • An array like [11, 22, 33, 44]
        • Object property that will evaluate to some value
        • Function call that returns value which may be JSX
        • map() method that always returns a new array
        • JSX itself
    8. In the JSX expression Example below, is used to find the area of a circle ; given the radius

      
       let radius = 12;
       const circleArea = <h1>Area = {3.142 * radius * radius} sq units</h1>; 
      
      

    9. 5. JSX will throw an error, if the HTML is NOT properly closed. Either use <App>...</App> or <App/>

    10. 6. Since class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX. Hence use ClassName
    11. In the JSX Example below, ClassName attribute is assigned the value "App"

      
      function App() {
        return (
          <div className="App"> 
            <h1>Hello World!</h1> 
          </div>
        );
      }
      
      export default App;
      
      

    12. 7. React supports if statements, but NOT inside JSX :
      • put the if statements outside of the JSX or
      • use a ternary expression instead
    13. In the JSX Example below, with if statements outside of the JSX:

      
      /* JavaScript statements */
      let age = 24,
          message;
      
      if (age < 19) {
          message = "NOT eligible to vote!";
      }
      else {
          message = "Eligible to vote!";
      }
      
      /* JSX statement */
      const heading = <h1>{message}</h1>;
      
      

      In the JSX Example below, using a ternary expression instead of if statements :

       
      /* Ternary expression in JSX code */
      
      let age = 24;
      const heading = (
        <h1>{age < 19 ? "NOT eligible to vote!" : "Eligible to vote!"}</h1>
      );
      
      

    14. 8. JSX prevents injection attacks, as it is safe to embed user input in JSX.

      By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that's not explicitly written in your application.

      Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

    15.  
      const title = response.potentiallyMaliciousInput;
      
      /* This is safe */
      const element = <h1>{title}</h1>; 
      
      

    16. 9. JSX represents Objects

      Babel compiles JSX down to React.createElement() calls.

      NOTE: Babel is a JavaScript compiler and transpiler that can transform modern JavaScript code into backward-compatible versions. JSX is not natively supported by browsers, so Babel is commonly used to transpile JSX code into plain JavaScript that browsers can understand.
      Transpiling is the process of taking source code written in one language and transforming it into another language that has a similar level of abstraction

    17. These two below examples are identical:

       
      const element = (
        <h1 className="greeting">
          Hello, world!
        </h1>
      );
      
      
       
      const element = React.createElement(
        'h1',
        {className: 'greeting'},
        'Hello, world!'
      );
      
      

      React.createElement() performs a few checks to help you write bug-free code but essentially it creates an object like this:

       
      /* Note: this structure is simplified */
      
      const element = {
        type: 'h1',
        props: {
          className: 'greeting',
          children: 'Hello, world!'
        }
      };
      
      

      These objects are called “React elements”. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.

    Rendering Elements

    What is meant by render?

  • Render means renew only an appropriate part of information on user's screen when the element properties (props) are replaced by new ones or a component state (as set of props) changes in application.
  • Thanks to the render method render(), we avoid reloading the whole web page, save time, and increase productivity.
  • What are Element?

  • Elements are the smallest building blocks of React apps. React components are made of Elements.
  • These elements are HTML DOM elements also named in React, the root nodes. Due to this, we apply for writing React files in JSX language - JavaScript syntax extension, which combines JavaScript and HTML syntax in the same file.
  • React's main purpose is to render HTML element in a web page. An element describes what you want to see on the screen:
  • 
    const element = <h1>Hello World!</h1>;
    
    
  • Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements.

  • Summary:

    1. React maintains its own image of what the DOM should look like, called virtual DOM. Calling render method render() updates that image.
    2. render() method is called every time React notices changes in component's (or its parent's) state or props. It gives React the most up-to-date information to update virtual DOM. In other words, update its image of what the component needs to look like.
    3. Sometimes a small change in a component's state triggers the re-render of all its children components in the component tree. This might seem inefficient, but React elements returned by the render() function are just plain JavaScript objects. Creating and updating them takes very little resources.
    4. React rerenders entire component trees to ensure that virtual DOM stays up to date with most recent changes in the app.
    5. To reiterate, render() updates virtual DOM, it does not directly update the HTML. React compares virtual DOM with actual HTML, and updates the actual DOM.

    Rendering an Element into the DOM

    Let's say there is a <div> somewhere in your HTML file:

    
    <div id="root"></div>
    
    

    We call this a “root” DOM node because everything inside it will be managed by React DOM.

    Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.

    React root node:

  • root node is a container for content managed by React
  • root node is the HTML element where you want to display the result
  • By default "root" uses the <div> html element at public/index.html file location
  • "root" can be of any other name and it can be any other HTML element as well
  • React will rendered to a "root" element in the HTML page

  • To render a React element, first pass the DOM element to ReactDOM.createRoot(), then pass the React element to root.render().

    It displays Hello World! on the webpage.

    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    const element = <h1>Hello World!</h1>;
    root.render(element);
                    
    

    React library's main purpose is to render HTML in a web page. React renders HTML to the web page by using a function called createRoot() and its method render() :

  • createRoot():
    • which takes one argument - an HTML element
    • defines the HTML element, where a React component (App) should be displayed
  • render()method of createRoot():
    • defines the React component that should be rendered
    • <div> with the id attribute as "root", in body of public/index.html file, is where, the React application will be rendered
  • Updating the rendered element

    React elements are immutable. Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.

    With our knowledge so far, the only way to update the UI is to create a new element, and pass it to root.render().

    Consider this ticking clock example. It calls root.render() every second from a setInterval() callback.

     
    const root = ReactDOM.createRoot(document.getElementById('root'));
    
    function displayTime() {
        const element = (
            <div>
                <h1>Hello World!</h1>
                <h2>Current time is {new Date().toLocaleTimeString()}.</h2>
            </div>
        );
        root.render(element);
    }
    
    setInterval(displayTime, 1000);
    
    
    OUTPUT
     

    React only updates what's necessary

    React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

    You can verify by inspecting the last example with the browser tools:

    react element render

    Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.

    In our experience, thinking about how the UI should look at any given moment, rather than how to change it over time, eliminates a whole class of bugs.

    React Components

    React is based on a component-based architecture, which means that the user interface is built by assembling individual components. Each component is responsible for rendering a part of the user interface. When a component is first mounted, React calls its render() method, which returns a React element, a lightweight description of what to render.

    React Components:

  • Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
  • React lets you combine your HTML, CSS and JavaScript into custom “components”, reusable UI elements for your app.
  • React component is a JavaScript function that returns HTML elements.
  • Components are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI).
  • Components accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
  • ReactJS Components

    The above displayed webpage layout can be represented by these React components:

    
    <PageLayout>
    
      <PageHeader>
        <HeaderLogo />
        <NavBar />
      </PageHeader>
    
      <MainPage>
        <SectionOne />
        <SectionTwo />
        <SectionThree />
        <SectionFour /> 
      </MainPage>
    
      <Sidebar />
      <PageFooter />
    
    </PageLayout>
    
    

    Functional Component

  • Functional components in React are a way to define components using JavaScript functions.
  • Components take in props (short for properties) as input and return a React element, which describes what should be rendered.
  • Functional components are simple and focused on rendering UI based on the provided props.
  • Components can be composed and nested, allowing you to create complex UI hierarchies.
  • Functional Components are also known as stateless components or presentational components.
  • Functional components are regular JavaScript functions, but their names must start with a capital letter or they won't work.
  • Older React code bases, encouraged Class components primarily to be used. On February 16, 2019, React 16.8 was released to the public, introducing React Hooks. Hence, Function Components are highly encouraged to be used in React.
  •  
    /* "App" Functional component that displays a message */
    
    function App() {
      return (
        <div className="App"> 
          <h1>Hello World!</h1> 
        </div>
      );
    }
    
    export default App;
    
    

    Rendering Functional Component

  • Rendering is the process of transforming your React components into DOM (Document Object Model) nodes, that your browser can understand and display on the screen.
  • React application has a component called App, which returns a <div> main element
  • To use this component in your web application, use similar syntax as normal HTML: <App />
  • 
    /* React is rendered to a root element in the HTML page */
    
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <>
        <App />
      </>
    );
    
    
    OUTPUT
     

    Hello World!

      Let's recap what happens in above example:
    1. 1. We call root.render() with the <App /> element.
    2. 2. React calls the App functional component.
    3. 3. Our App component returns a <h1>Hello World!</h1> element as the result.
    4. 4. React DOM efficiently updates the DOM to match <h1>Hello World!</h1>.

    Nested Components

  • Nested components refer to the practice of composing components by nesting them within each other.
  • This allows you to create complex user interfaces by combining smaller, reusable components together.
  • Components can render other components, but you must never nest their definitions. This will be very slow and causes bugs
  • When a child component needs some data from a parent, pass it by props instead of nesting definitions.
  • Here's an example to illustrate nested components:

     
    function Header() {
        return <h2>Header Component</h2>;
    }
    
    function Content() {
        return (
            <div>
                <h2>Content Component</h2>
                <p>This is the content area.</p>
            </div>
        );
    }
    
    function Footer() {
        return <p>Footer Component</p>;
    }
    
    function App() {
        return (
            <div>
                <Header />
                <Content />
                <Footer />
            </div>
        );
    }
    
    export default App;
    
    
    OUTPUT
     

    Header Component

    Content Component

    This is the content area.

    Footer Component

    In the example above, the App component serves as the root component, which renders a <div> element containing three nested components: Header, Content, and Footer. Each of these nested components is a separate functional component responsible for rendering a specific part of the UI.

    By nesting components, you can break down the UI into smaller, reusable pieces. This promotes a modular approach where each component focuses on a specific task or UI element. The Header component can handle the rendering of the application's header, the Content component can handle the main content area, and the Footer component can handle the rendering of the footer.

    Nested components can be used to build more complex UI hierarchies as well. For example, you can have a UserList component that renders individual UserItem components, which in turn may include nested components such as Avatar or UserInfo. This nesting structure allows you to create a rich and interactive user interface.

    By composing components in a nested manner, you can achieve code reusability, separation of concerns, and maintainability. Each component can be independently developed, tested, and reused in different parts of your application.

    Components in separate Files

  • Components are typically defined in separate files to promote code organization and maintainability.
  • Each component is usually placed in its own file, and the file name matches the component's name.
  • You can move a component in three steps:

  • Make a new JavaSscript file to put the components in.
  • Export your function component from that file (using either default or named exports).
  • Import it in the file where you'll use the component (using the corresponding technique for importing default or named exports).
  • Here's an example of how React components can be organized in separate files:

    1. Header.js:

     
    import React from "react";
    
    function Header() {
        return <h2>Header Component</h2>;
    }
      
    export default Header;
    
    

    2. Content.js:

      
    import React from "react";
        
    function Content() {
        return (
            <div>
                <h2>Content Component</h2>
                <p>This is the content area.</p>
            </div>
        );
    } 
        
    export default Content;
        
    

    3. Footer.js:

     
    import React from "react";
    
    function Footer() {
        return <p>Footer Component</p>;
    }
    
    export default Footer; 
          
    

    4. App.js:

     
    import React from 'react';
    import Header from './Header';
    import Content from './Content';
    import Footer from './Footer';
            
    function App() {
        return (
            <div>
                <Header />
                <Content />
                <Footer />
            </div>
        );
    }
    
    export default App;
            
    

    In this example, each component is defined in a separate file and exported using the export default syntax. Other components can import them using the import statement and use them within their own code.

    The App component serves as the root component and imports the Header, Content, and Footer components. It then uses these components to compose the overall UI structure.

    By organizing components in separate files, it becomes easier to locate, understand, and maintain specific parts of the application. This modular approach improves code reusability and allows for better collaboration among team members.

    Note that the file structure and naming conventions may vary based on the project's needs and development practices. However, it is generally recommended to keep components in separate files for better organization and readability.

    React Props (short for properties)

  • In React, props (short for properties) are a mechanism for passing data from a parent component to its child components.
  • Props allow you to customize the behavior or appearance of a component dynamically by providing values or functions as attributes.
  • You can pass any JavaScript value through them, including objects, arrays, and functions.
  • React Props are like function arguments in JavaScript and attributes in HTML.
  • React functional component accept a single argument, a props object
  • All React components must act like pure functions with respect to their props. Functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.
  • React Props are read-only. You will get an error if you try to change their value.
  • You can't change props. When you need interactivity, you'll need to set state.
  • Props are read-only snapshots in time: every render receives a new version of props.
  • Here's an example to illustrate the usage of props:

    
    /* child Component - Greeting */
    function Greeting(props) {
      return <h1>Hello, {props.name}!</h1>;
    }
    
    /* parent Component - App */
    function App() {
      return (
        // To send props into a component, use the same syntax as HTML attributes
        <div>
          <Greeting name="Seeta" /> 
          <Greeting name="Geeta" />
        </div>
      );
    }
    
    
    OUTPUT
     

    Hello, Seeta!

    Hello, Geeta!

    In the above example, the Greeting component is rendered twice within the App component. The name prop is passed with different values, resulting in two greetings being displayed: "Hello, Seeta!" and "Hello, Geeta!".

    React props : Send Data as an object

  • If you have a variable/object to send, you just put the variable/object name inside curly brackets { }
  • Populate the dynamic values from the object using the dot (.) notation
  • Here's a complete example to demonstrate passing props to a child component:

    1. Code in ParentComponent.js file

    
    import React from 'react';
    import ChildComponent from './ChildComponent';
    
    function ParentComponent() {
      // an object named "info"
      const info = { name: 'Rohit.', age: 25 };
      // define the child component and provide the desired prop(s) as attributes
      return ( <ChildComponent infoAttr = {info} /> );
    }
    
    export default ParentComponent;
    
    

    2. Code in ChildComponent.js file

    
    import React from 'react';
    
    // access the passed props using the props object and dot (.) notation
    function ChildComponent(props) {
      return (
        <h1>
          My name is {props.infoAttr.name}. I am {props.infoAttr.age} years old.
        </h1>
      );
    }
    
    export default ChildComponent;
    
    
    OUTPUT
     

    My name is Rohit. I am 25 years old.

    In the example above, the ParentComponent renders the ChildComponent and passes two props: greeting and age. The ChildComponent receives these props through the props object and renders their values.

    Forwarding props with JSX spread syntax ...

    Sometimes, passing props gets very repetitive:

    
    function Profile ( { person, size, isSepia, thickBorder } ) {
      return (
        <div className="card">
          <Avatar
            person={person}
            size={size}
            isSepia={isSepia}
            thickBorder={thickBorder}
          />
        </div>
      );
    }
    
    

  • There's nothing wrong with repetitive code - it can be more legible. But at times you may value conciseness.
  • Some components forward all of their props to their children, like how this Profile does with Avatar. Because they don't use any of their props directly, it can make sense to use a more concise “spread” syntax:
  • 
    function Profile(props) {
      return (
        <div className="card">
          <Avatar {...props} />
        </div>
      );
    }
    
    

    This forwards all of Profile's props to the Avatar without listing each of their names.

    Use spread syntax with restraint. If you're using it in every other component, something is wrong. Often, it indicates that you should split your components and pass children as JSX. More on that next!

    React conditional rendering

  • React conditional rendering refers to the practice of conditionally rendering components or elements based on certain conditions.
  • It allows you to control what content gets displayed in the UI based on the state or props of the component.
  • In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators.
  • You can use JavaScript expressions and logical operators to conditionally render components, elements, or even entire sections of your UI based on the desired conditions.
  • Here are a few common ways to perform conditional rendering in React:

    1. if / else statements:

    In this example, the isLoggedIn prop is used to conditionally render different content. If isLoggedIn is true, the App component renders a welcome message; otherwise, it renders a message asking the user to log in.

    
    function App ({ isLoggedIn }) {
      if (isLoggedIn) {
        return <p>Welcome, user!</p>;
      } 
      else {
        return <p>Please log in to continue.</p>;
      }
    }
    
    

    2. Ternary Operator ? : statements:

    Here, the count prop is used in a ternary operator to conditionally render different elements. If count is greater than zero, it renders a paragraph showing the actual count value; otherwise, GetCount component renders a message indicating no count is available.

    
    function GetCount ({ count }) {
      return (
        <div>
          { count > 0 ? <p>Count: {count}</p> : <p>No count available.</p> }
        </div>
      );
    }
    
    

    3. Logical &&Operator:

    In this example, the isLoaded prop is used with the logical && operator to conditionally render the paragraph element. If isLoaded is true, the paragraph showing the loaded data is rendered; otherwise, nothing is rendered.

    
    function GetData ({ isLoaded, data }) {
      return (
        <div>
          { isLoaded && <p>Data loaded: {data}</p> }
        </div>
      );
    }
    
    

    4 Using Inline Functions & / or if statements:

    Here, an inline function is used to perform the conditional rendering based on the condition prop. The function checks the condition and returns the appropriate content.

    
    function MyComponent ({ condition }) {
      return (
        <div>
          {(() => {
            if (condition) {
              return <p>Condition is true.</p>;
            } 
            else {
              return <p>Condition is false.</p>;
            }
          })()}
        </div>
      );
    }
    
    

    Preventing Component from Rendering

    In React, you may encounter situations where you want to prevent a component from rendering under certain conditions. There are a few approaches you can take to achieve this.


    Conditional Rendering:

    You can conditionally render the component based on a specific condition. If the condition is not met, you can choose to render null or an empty fragment (<>...</>) instead of the component. This prevents the component from rendering.

    In the below example, if the shouldRender prop is false, the component returns null, and nothing is rendered. If shouldRender is true, the component renders the <p> element with the content. </p>

     
    function MyComponent ({ shouldRender }) {
      if (!shouldRender) {
        return null; // or return <> </>;
      }
    
      return <p>Rendered content</p>;
    }
    
    

    Component State:

    You can use component state to control whether the component should render or not. You can conditionally update the state and trigger a re-render of the component based on specific conditions.

    In this below example, the component initially sets shouldRender to false. Using the useEffect hook, you can conditionally update the state based on your condition. If shouldRender is false, the component returns null, preventing the rendering of the content.

     
    import React, { useState, useEffect } from 'react';
    
    function MyComponent() {
      const [shouldRender, setShouldRender] = useState(false);
    
      useEffect(() => {
        // Conditionally update the state
        if (/* your condition */) {
          setShouldRender(true);
        }
      }, []);
    
      if (!shouldRender) {
        return null; // or return <></>;
      }
    
      return <p>Rendered content</p>;
    }
    
    export default MyComponent;
    
    

    React Events

  • Events are used to handle user interactions such as mouse clicks, keyboard input, or form submissions.
  • React provides a synthetic event system that wraps the native browser events and provides a consistent API across different browsers.
  • Handling events with React elements is very similar to handling events on DOM elements. Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
  • React events are written in camelCase syntax. Example: onclick event will be onClick instead
  • React event handlers are written inside curly braces { }. Example: onClick = {thankYou}
  • To pass an argument to an event handler, use an arrow function ( => )
  • Adding event handlers

    To add an event handler, you will first define a function and then pass it as a prop to the appropriate JSX tag.

    For example, here is a button, You can make it show a message when a user clicks by following these three steps:

  • Declare a function called handleClick inside your Button component.
  • Implement the logic inside that function (use alert to show the message).
  • Add onClick = {handleClick} to the <button> JSX.
  • Event handlers must be passed, not called. <button onClick={handleClick}>, not <button onClick={handleClick()}>
  • 
    function Button() {
      function handleClick() {
        alert('You clicked me!');
      }
    
      return (
        <button onClick = {handleClick}>
          Click me
        </button>
      );
    }
    
    export default Button;
    
    
    OUTPUT
     
    
    
    

    You defined the handleClick function and then passed it as a prop to <button>. handleClick is an event handler. Event handler functions:

  • Are usually defined inside your components.
  • Have names that start with handle, followed by the name of the event.
  • Passing Arguments

    By using an arrow function ( => ), we can pass an argument to an event handler

    
    function ShoppingDone() {
      function thankYou (ty) {
        alert(ty);
      };
    // Using an arrow function, passing an argument to event handler
    return (
      <button onClick={() => thankYou("Thank you for shopping!")}>
          Thankyou Note
      </button> 
    );
    } 
    
    export default ShoppingDone;
    
    
    OUTPUT
     
    
    
    

    Rendering Lists

  • You will often want to display multiple similar components from a collection of data. You can use the JavaScript array methods to manipulate an array of data.
  • filter() and map() methods, are used in React to filter and transform your array of data into an array of components.
  • Rendering lists in React involves dynamically generating components or elements based on an array or iterable of data.
  • It allows you to display a collection of items in the UI without explicitly writing individual components for each item.
  • Rendering Multiple Components

  • To render a list (containing multiple similar components), you can use the filter() or map() methods, to iterate over the data and create a new array of React components or elements.
  • Each item in the data array is mapped to a corresponding component or element.
  • Example: In the below example, the items array contains strings representing fruit names. The map() method is used to create an array of <li> elements, where each fruit name is rendered as a list item.

    Keys:

  • Note the usage of the key prop in the <li> elements. It helps React identify each list item uniquely and optimize the rendering process.
  • The key should be a unique identifier for each item, such as an ID from the data source.
  • Keys allow React to keep track of elements. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list.
  • key is a restricted keyword in React.
  • Where to get your key: Different sources of data provide different sources of keys:

  • Data from a database: If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
  • Locally generated data: If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter, crypto.randomUUID() or a package like uuid when creating items.
  • Rules of keys:

  • Keys must be unique among siblings. However, it's okay to use the same keys for JSX nodes in different arrays.
  • Keys must not change or that defeats their purpose! Don't generate them while rendering.
  • 
    function FavFruits () {
      const items = ['Apple', 'Banana', 'Orange'];
    
      return (
        <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      );
    }
    
    export default FavFruits;
    
    
    OUTPUT

  • Apple
  • Banana
  • Orange
  • Rendering custom components

    Instead of rendering simple elements like <li>, you can also render custom components for each item in the list.

    Example: In the below example, the FruitList component renders a list of custom FruitItem components. Each FruitItem component receives the name & id props to display the fruit name & key value.

    
    function FruitItem({ name, id }) {
      return <li>{name} (key value = {id})</li>;
    }
    
    function FruitList() {
      const fruits = [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Orange' },
      ];
    
      return (
        <ul>
          {fruits.map((fruit) => (
            <FruitItem key={fruit.id} name={fruit.name} id={fruit.id}/>
          ))}
        </ul>
      );
    } 
    
    export default FruitList;
    
    
    OUTPUT

  • Apple (key value = 1)
  • Banana (key value = 2)
  • Orange (key value = 3)
  • React Forms

  • React forms are used to capture user input and handle form submissions in a React application.
  • React Forms provide a way to collect data from users and update the application's state or send the data to a server.
  • Just like in HTML, React uses forms to allow users to interact with the web page.
  • Add Forms in React

    You can add forms in React app, like adding another other elements.

    In the Example below, adding a form which accepts OTP (one time password) number :

    
    export default function ValidateOTP() {
      return (
        <form>
          <label>Enter the OTP:
              <input type="text" />
          </label> 
        </form>
      );
    }  
    
    
    OUTPUT
      

    Handling Forms input & submit

  • In React, form elements such as <input>, <textarea>, and <select> are used to capture user input. Each form element typically has a corresponding state in the component to hold the user's input.
  • Handling forms is about how you handle the data when it changes value or gets submitted.
  • In HTML, form data is usually handled by the DOM. In React, form data is usually handled by the components.
  • When the data is handled by the components, all the data is stored in the component state.
  • You can control changes by adding event handlers in the onChange attribute.
  • We can use the useState Hook to keep track of each inputs value and provide a "single source of truth" for the entire application.
  • You can control the submit action by adding an event handler in the onSubmit attribute for the <form>
  • Example: In this example, the ValidateOTP component renders a form with one input field for OTP. The state hook otp is used to hold the current values of the input field. The onChange event handler update the state value.

    The handleSubmit function is called when the form is submitted i.e. onSubmit = {handleSubmit} .You can process the form data, perform validation, and handle the submission logic within this function.

    
    import { useState } from 'react';  
    
    function ValidateOTP() {
      const [otp, setOTP] = useState("");
      
      const handleSubmit = () => {
        alert('OTP has been validated!')
      }
    
      return (
        <form  onSubmit = {handleSubmit} >
          <label>Enter the OTP:
            <input
              type="text" 
              value={otp}
              onChange={(event) => setOTP(event.target.value)}
            />
          </label>
          <input type="submit" />
        </form>
      )
    }
    
    export default ValidateOTP;
    
    
    OUTPUT
      

    Handling multiple Inputs

  • You can control the values of more than one input field by adding a name attribute to each element.
  • Initialize state with an empty object.
  • In order to access the fields in the event handler use the event.target.name and event.target.value syntax.
  • In order to update the state, use square brackets [bracket notation] around the property name.
  • 
    
    import { useState } from 'react';
    import ReactDOM from 'react-dom/client';
    
    function LoginApp() {
      const [inputs, setInputs] = useState({});
    
      const handleChange = (event) => {
        const name = event.target.name;
        const value = event.target.value;
        setInputs(values => ({...values, [name]: value}))
      }
    
      const handleSubmit = () => {
        alert('Login Successful, Welcome back!'); 
      }
    
      return (
        <form onSubmit = {handleSubmit} >
          <label>Username:
          <input 
            type="text" 
            name="username" 
            value={inputs.username || ""} 
            onChange={handleChange}
          />
          </label>
          <label>Password:
            <input 
              type="password" 
              name="pass" 
              value={inputs.pass || ""} 
              onChange={handleChange}
            />
            </label>
            <input type="submit" />
        </form>
      )
    }
    
    export default LoginApp;
    
    
    OUTPUT
      

    React Hooks

  • React Hook is a special JavaScript function provided by React that allows you to add additional features to functional components.
  • React Hooks enables you to use state, lifecycle methods, and other React features without writing a class component.
  • React Hooks can be stateful and can manage side-effects.
  • React Hooks were introduced in React 16.8 as a way to simplify state management and reuse code logic.
  • React Hooks will not work in React class components.
  • Characteristics of Hooks

  • Hooks are functions: Hooks are regular JavaScript functions that can be called in functional components. They cannot be used in class components.
  • Hooks start with "use": All hooks provided by React start with the prefix "use". This naming convention helps differentiate them from regular functions and makes it easier to identify hooks in the codebase.
  • Hooks provide additional features: Hooks enable functional components to have features such as state management, side effects, context access, memoization, and more. Each hook serves a specific purpose and allows you to enhance your components with specific functionality.
  • Standard in-built Hooks

    React provides a bunch of standard in-built hooks.

  • useState : To manage states. Returns a stateful value and an updater function to update it.
  • useEffect : To manage side-effects like API calls, subscriptions, timers, mutations, and more.
  • useContext : To return the current value for a context.
  • useReducer : A useState alternative to help with complex state management.
  • useCallback : It returns a memorized version of a callback to help a child component not re-render unnecessarily.
  • useRef : It returns a ref object with a current property. The ref object is mutable. It is mainly used to access a child component imperatively.
  • useLayoutEffect : It fires at the end of all DOM mutations. It's best to use useEffect as much as possible over this one as the useLayoutEffect fires synchronously.
  • useDebugValue : Helps to display a label in React DevTools for custom hooks.
  • NOTE: If you have stateful logic that needs to be reused in several components, you can build your own custom Hooks.

    3 React Hook Rules

    React hooks come with three fundamental rules that should be followed to ensure their correct usage:

  • Only Call Hooks at the Top Level: React hooks should be called at the top level of functional components or within other custom hooks. They should not be called within loops, conditions, or nested functions. This rule ensures that hooks are called consistently and in the same order on every render, allowing React to maintain the correct state and perform optimizations.
  • Only Call Hooks from React Functions: Hooks should only be called from within React functional components or custom hooks. They should not be called from regular JavaScript functions, event handlers, or asynchronous operations outside of React components. This rule ensures that hooks are used within the React component lifecycle and allow React to manage their state and lifecycle automatically.
  • Hooks cannot be conditional: React hooks should not be called conditionally within functional components. React hooks rely on the order of their calls to maintain consistent state and ensure that the correct hooks are associated with the correct component instances. If hooks are called conditionally, it can lead to unexpected behavior and bugs.
  • ReactJS Interview Questions

    Get the hold of actual interview questions during job hiring.

    What is React?

    React is a JavaScript library used for building user interfaces. It allows developers to create reusable UI components and efficiently update the UI based on changes in data.

    What are the key features of React?

    Some key features of React include virtual DOM for efficient rendering, component-based architecture, declarative syntax, and the ability to create reusable UI components.

    What is JSX?

    JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It is commonly used with React to define the structure and content of components.

    What is the difference between a functional component and a class component?

    Functional components are simpler and rely on JavaScript functions to define the component. They are used for simpler UI elements. Class components are more feature-rich and use ES6 classes to define the component. They have additional lifecycle methods and state management capabilities.

    What is the purpose of state in React?

    State is a JavaScript object used to store and manage component-specific data. It allows components to have dynamic behavior and enables them to update and re-render based on changes to the state.

    What are React hooks?

    React hooks are functions that allow you to use state and other React features in functional components. They were introduced in React 16.8 and provide an alternative to using class components.

    What is the significance of the "key" prop in React lists?

    The "key" prop is used to provide a unique identifier to each item in a list rendered by React. It helps React efficiently update and reorder the list elements when changes occur, improving performance.

    What is the purpose of the componentDidMount lifecycle method?

    The componentDidMount method is called after a component has been rendered to the DOM. It is commonly used for tasks such as initializing data, making API calls, or setting up event listeners.

    How can you optimize the performance of a React application?

    Some performance optimization techniques for React include minimizing unnecessary re-rendering, using memoization techniques like memo and useMemo, code splitting, and lazy loading components.

    What is the role of Redux in React?

    Redux is a state management library that helps manage the global state of a React application. It provides a centralized store to store application state and allows components to access and update that state.

    What are React components?

    React components are independent, reusable building blocks that encapsulate the UI logic and can be composed together to build complex user interfaces. Components can be either functional or class-based.

    What is the difference between controlled and uncontrolled components in React?

    In controlled components, the component's state is controlled by React. The component receives its current value and a callback function to update the value from the parent component. In uncontrolled components, the component maintains its own internal state without relying on React.

    What is the purpose of the "setState" method in React?

    The "setState" method is used to update the state of a React component. It takes an object or a function as an argument and merges the new state with the existing state, triggering a re-render of the component.

    What is the significance of the "useEffect" hook?

    The "useEffect" hook is used to perform side effects in functional components. It allows you to run code in response to component mounting, updating, or unmounting. It can be used for tasks such as fetching data, subscribing to events, or manipulating the DOM.

    Explain the concept of virtual DOM in React.

    The virtual DOM is a lightweight copy of the actual DOM maintained by React. It is a representation of the UI and its state. When there are changes in the data or state, React compares the virtual DOM with the real DOM and efficiently updates only the necessary parts, minimizing performance overhead.

    What are React Router and its benefits?

    React Router is a popular library used for handling routing in React applications. It allows you to define different routes and map them to specific components. React Router provides a seamless navigation experience within a single-page application (SPA) and enables bookmarking and sharing of specific URLs.

    What is prop drilling and how can it be avoided?

    Prop drilling refers to the process of passing props through multiple intermediate components that don't need them, just to reach a deeply nested component. It can make the codebase harder to maintain and understand. Prop drilling can be avoided by using techniques like React context or Redux to manage and share state across components.

    What is React.memo and when should it be used?

    React.memo is a higher-order component (HOC) that memoizes the result of a component rendering. It helps in optimizing performance by preventing unnecessary re-rendering of components. React.memo should be used for functional components that receive the same props and always produce the same result.

    Explain the concept of code splitting in React.

    Code splitting is a technique used to split the JavaScript bundle generated by Webpack into smaller chunks. This allows for lazy loading of components and resources, loading only the necessary code when needed. It helps in reducing the initial load time and improves the performance of the application.