React

Latest Version:

V19 (Dec 2024)

Definition:

  • It’s a Javascript Library developed by Facebook.
  • It allows you to create a single page application.
  • We should use the react because using react, the reusable UI components can be created easily. Infact, react is all about reusing code. It’s a flexible and lightweight tool for building UI components.

How does it work?

  • React creates a VIRTUAL DOM in memory.
  • Instead of manipulating the browser’s DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulating, before making the changes in the browser DOM.
  • React only changes what needs to be changed!

HTML Rendering:

  • const myVar = ‘Hello Dear’
  • ReactDom.render(myVar, document.getElementById(‘root’))

Features:

  • Components: ReactJS is all about components.
  • virtual dom
  • One-way Data Binding

Components:

  • Independent and reusable code
  • returns HTML via a render function
  • 2 types :: Class components and Function components

Creating a component:

  • component’s name must start with an uppercase letter
  • extends React.Component
  • component requires a render() method
  • To use the component:  use syntax as normal HTML: <Car />

Props:

  • Props are arguments passed into the React components using HTML attributes.

State Object:

  • React components have a built-in state object.
  • The state object is where you store property values that belong to the component.
  • When the state object changes, the component re-renders.

To change state object:

this.setState({color: “blue”});

Component Life Cycle:

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.

  1. Mounting which means, putting elements into the DOM. The execution includes following 4 methods:

2. Updating:

The next phase in the life cycle is when a component is updated using change in state or props. Following 5 methods are made for update:

3. Unmounting: The next phase in the life cycle is when a component is removed from the DOM, or unmounting as React likes to call it.

componentWillUnmount: 

It is called when the component is about to be removed from the DOM.

Super(props):

By calling the super() method in the constructor method, we call the parent’s constructor method

ES6 or ECMAScript 6 or ECMAScript 2015:

ECMAScript is used to standardize JavaScript

ES6 Arrow Function: Arrow functions allow us to write shorter function 

hello = () => “Hello World!”; // hello is a function, which returns “Hello World”

hello = (val) => “Hello ” + val;

hello = val => “Hello ” + val;

ES6 Variables:

var

let: let is limited to the block (or expression) where it is defined.

      If you use let inside a for loop, the variable is only available inside of that loop.

const: const is a variable that once it has been created, its value can never change.

JSX:  

  • Stands for JavaScript XML 
  • It allows us to write HTML in React
  • It makes it easier to write and add HTML in React
  • It is an extension of the JavaScript language based on ES6

Examples of JSX:

const myelement = <h1>I Love JSX!</h1>;

expressions are written inside the curly braces like this: {5 + 5}

HTML elements must be properly closed <input type=”text” />

Pros:

React is all about creating reusable components

Good Performance because of virtual dom

It’s simple and easy to learn and so it saves development time as well.

Cons:

Complex State Management is still incomplete. Like in the recent version of react, they introduced useReducer hook for handling complex states.

Possibility of Boilerplate Code in react is higher then angular and vue

Code:

const container = document.getElementById(“root”);

const root = ReactDOM.createRoot(container);

root.render(<Hello />);

Importing a component:

import React, { Component } from ‘react’;

Events:

React has the same events as HTML: click, change, mouseover etc.

onClick={shoot}

this: 

For methods in React, “this“ keyword should represent the component that owns the method.

That’s why, we should use arrow functions, so that, “this“ will always represent the object that defined the arrow function.

Otherwise, “this” will represents the object that called the method, which can be the global window object, a HTML button, or whatever.

In case you have to use the regular functions instead of arrow functions, you have to bind “this” to the component instance using the bind() method

ES6 Class:

In terms of OOPs, a class is a template definition of the methods and variables in a particular kind of object. but in terms of React, a class is a type of function.

  • Object oriented class is supported here.
  • Constructor function, inheritance (extend another class), object creation everything is same like OOP’s
  • The super() method refers to the parent class.

ES6 Destructuring:

const vehicles = [‘mustang’, ‘f-150’, ‘expedition’];

const [car,, suv] = vehicles;

ES6 Spread Operator:

const newArray = […array1, …array2];

Babel:

Babel is a JavaScript compiler that converts modern JavaScript code into a version compatible with all browsers. So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler. 

You can set up your own babel configuration using Webpack. Or you can use create-react-app which internally uses Babel for the JSX to the JavaScript conversion.

React Hooks:

Hooks are simply the javascript functions which are used in the functional component for the purpose of providing it access to the react state and other features, so that we do not need the class compoent.

It simply isolate the reusable part from a functional component.

For example, we can use useMemo hook to memorise a particular state/data in a function component, which is called more than one time. So for the same purpose, it was required to create a class component in which an internal state can keep the value in memory but after introducing useMemo hook, a function component is itself sufficient for doing the whole thing. 

Even useCallback hook is introduced in react 16, which is used to memorise the whole callback function, so it does not required to recalculate the values and which will help to prevent rendering DOM if the calculate result is same.

memo:

Used to skip rendering a component if its props have not changed.

Hook rules:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.

Hooks cannot be conditional:

  • useState: Used to keep track of state of properties or data in a function component.
  • useEffect: This hook allows to perform the side effects in your components.
  • useContext: Used to manage state globally
  • useRef: This will prevent reRender of the whole component just by changing the reference value. It deals with the DOM
  • useMemo: Use to return a momorized value, so that it does not need to be recalculated like 

const calculation = useMemo(() => expensiveCalculation(count), [count]);

  • useCallback: used to return a memoized callback function, so that it does not need to be recalculated.
    • Every time a component re-renders, its functions get recreated.
    • If we use, useCallback, the functions will be memorised, so we can prevent recalculating them or rerendering something as per our logic.
  • useReducer: In case when you have to keep track of multiple states and based on the user action, you have to keep changing the state,,,,you can use reducer. It’s one of the fantastic hook which is made to handle multiple states of an complete cycle let’s say you have to set the state = breakfast or lunch or dinner based on the current time, you can use reducer.

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

  • Information about above code line:
    • initialState : Initial state
    • reducer: A custom function which will change state based on action. state and action are the input parameters.
    • state: New state
    • dispatch: Used to dispatch the action (generally called from onclick function.)
  • array.reduce: When it is required to perform a operation on all the values of an array, then instead of using a loop, we can use array.reduce, in which a callback function is passed as a first argument, which is called recursively and an initial value is also passed as second argument.

users.reduce((prev, curr, index, array) => prev + curr.age, 0)

ReactDOM.hydrate: It allows to display a react component inside an existing DOM which is already rendered at the browser using react server.

create-react-app: It’s a tool for creating react application

React.lazy: Used for lazy loading components.

Diff between Angular and React:

  • React is a JavaScript library, whereas Angular is a front-end framework. 
  • React uses one-way data binding and virtual DOM, whereas Angular uses two-way data binding and real DOM. Moreover, React is faster than Angular as it has a smaller bundle size.

How to create a component:

Creating a new class which is extending React.Component and having basic functions like construct, render and anything as per that component requirement, that can be called as a component.

Changelong:

  • 16.6: Add support for contextType, Safari Issues
  • 16.7: Fix performance of React.lazy for lazily-loaded components, Fix bug with SSR
  • 16.8: Added hooks, 
    • Added ReactTestUtils.act() for batching updates
    • Support synchronous thenables passed to React.lazy()
    • Improve useReducer Hook lazy initialization API
    • Added ReactTestRenderer.act()
  • 18.0: Added new hook useId for generating unique id at server and client.
    • Added new hook useInsertionEffect, which allows CSS-in-JS libraries to address performance issues of injecting styles in render. 
    • Added new method createRoot which is used for creating a root for rendering or unmounting.
    • Added new method hydrateRoot to replace ReactDOM.hydrate
    • Note: If we are migrating from 17 to 18, it is must to use this method instead of ReactDOM.render, otherwise react 18 will produce warnings and will run application in 17.
    • Depereciated: ReactDOM.render, ReactDOM.hydrate, 
  • 18.1: Added more properties to the userId Hook,
    • Fixed many errors and warnings which are appeard in some special cases
    • Fix useDeferredValue causing an infinite loop when passed an unmemoized value.
  • 18.2: Fixed safary issu

Sass

  • Sass is a CSS pre-processor.
  • Sass files are executed on the server and sends CSS to the browser.
  • Command to install Sass package: npm install node-sass
  • Extension .scss
  • In Sass files you can use variables and other Sass functions
  • Import the Sass file the same way as you imported a CSS file