ReactJs in Sort

About React:

  • React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library created by Facebook.
  • React is a JavaScript library for building user interfaces.
  • React is used to build single-page applications.
  • React allows us to create reusable UI components.
  • React is a tool for building UI components.

How does React 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.JS History :

  • Current version of React.JS is V18.0.0 (April 2022).
  • Initial Release to the Public (V0.3.0) was in July 2013.
  • React.JS was first used in 2011 for Facebook’s Newsfeed feature.
  • Facebook Software Engineer, Jordan Walke, created it.
  • Current version of create-react-app is v5.0.1 (April 2022).
  • create-react-app includes built tools such as webpack, Babel, and ESLint.

React Getting Started:

  • To use React in production, We need npm which is included with Node.js.
  • To get an overview of what React is, you can write React code directly in HTML.

React Directly in HTML:

Example:

<!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>

</head>

<body>

<div id=”mydiv”></div>

<script type=”text/babel”>

function Hello() {

return <h1>Hello Baba!</h1>;

}

const container = document.getElementById(‘mydiv’);

const root = ReactDOM.createRoot(container);

root.render(<Hello />)

</script>

</body>

</html>

*** This way of using React can be OK for testing purposes, but for production you will need to set up a React environment.

Setting up a React Environment:

  • Run this command to create a React application named my-react-app:
    • npx create-react-app my-react-app
  • Run the React Application :
    • Run this command to move to the my-react-app directory:
      • cd my-react-app
  • Run this command to run the React application my-react-app:
    • npm start

=> A new browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000 in the address bar.

Default ReactJs Structure:

Modify the React Application:

  • Inside the src folder there is a file called App.js, open it and it will look like this:

/myReactApp/src/App.js:

import logo from ‘./logo.svg’;

import ‘./App.css’;

function App() {

return (

<div className=”App”>

<header className=”App-header”>

<img src={logo} className=”App-logo” alt=”logo” />

<p>

Edit <code>src/App.js</code> and save to reload.

</p>

<a

className=”App-link”

href=”https://reactjs.org”

target=”_blank”

rel=”noopener noreferrer”

>

Learn React

</a>

</header>

</div>

);

}

export default App;

  • Try changing the HTML content and save the file.

** Notice that the changes are visible immediately after you save the file, you do not have to reload the browser!

Example:

function App() {

return (

<div className=”App”>

<h1>Hello World!</h1>

</div>

);

}

export default App;

  • Now you have a React Environment on your computer, and you are ready to learn more about React.
  • In the rest of this tutorial we will use our “Show React” tool to explain the various aspects of React, and how they are displayed in the browser.

If we want to follow the same steps on our computer, start by stripping down the src folder to only contain one file: index.js. You should also remove any unnecessary lines of code inside the index.js file to make them look like the example in the “Show React” tool below:

Example:

index.js:

import React from ‘react’;

import ReactDOM from ‘react-dom/client’;

const myFirstElement = <h1>Hello React!</h1>

const root = ReactDOM.createRoot(document.getElementById(‘root’));

root.render(myFirstElement);

Test Yourself With Exercises:

Exercise:

Enter the correct ReactDOM method to render the React element to the DOM.

ReactDOM._____(myElement, document.getElementById(‘root’));

Ans: createRoot

Upgrading an existing React application to version 18 only requires two steps.

  • If you are already using the latest version of create-react-app which uses React version 18 you can skip this section.
  • Step 1: Install React 18
    • To install the latest version, from your project folder run the following from the terminal:
      • npm i react@latest react-dom@latest
  • Step 2: Use the new root API :
    • In order to take advantage of React 18’s concurrent features you’ll need to use the new root API for client rendering.

// Before

import ReactDOM from ‘react-dom’;

ReactDOM.render(<App />, document.getElementById(‘root’));

// After

import ReactDOM from ‘react-dom/client’;

const root = ReactDOM.createRoot(document.getElementById(‘root’));

root.render(<App />);

What is ES6?

  • ES6 stands for ECMAScript 6.
  • ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

Why Should I Learn ES6?

  • React uses ES6, and you should be familiar with some of the new features like:

* Classes

* Arrow Functions

* Variables (let, const, var)

* Array Methods like .map()

* Destructuring

* Modules

* Ternary Operator

* Spread Operator

Classes:

  • A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.

Example:

A simple class constructor:

class Car {

constructor(name) {

this.brand = name;

}

}

** Notice the case of the class name. We have begun the name, “Car”, with an uppercase character. This is a standard naming convention for classes.

create objects using the Car class:

class Car {

constructor(name) {

this.brand = name;

}

}

const mycar = new Car(“Ford”);

Method in Classes:

class Car {

constructor(name) {

this.brand = name;

}

present() {

return ‘I have a ‘ + this.brand;

}

}

const mycar = new Car(“Ford”);

mycar.present();

Class Inheritance:

  • To create a class inheritance, use the extends keyword.
  • A class created with a class inheritance inherits all the methods from another class:

Example:

class Car {

constructor(name) {

this.brand = name;

}

present() {

return ‘I have a ‘ + this.brand;

}

}

class Model extends Car {

constructor(name, mod) {

super(name);

this.model = mod;

}

show() {

return this.present() + ‘, it is a ‘ + this.model

}

}

const mycar = new Model(“Ford”, “Mustang”);

mycar.show();

  • **The super() method refers to the parent class.
  • ** By calling the super() method in the constructor method, we call the parent’s constructor method and get access to the parent’s properties and methods.

Arrow Functions:

Arrow functions allow us to write shorter function syntax:

Example:

Before:

hello = function() {

return “Hello World!”;

}

With Arrow Function:

hello = () => {

return “Hello World!”;

}

**If you have only one parameter, you can skip the parentheses as well:

hello = val => “Hello ” + val;

React Component Lifecycle method:

  • The render() method is used to render HTML of the component in reactjs.
  • This method is required in class bassed component to render DOM.

Some Lifecycle methods are:

Mounting Phase:

constructor():

  • This is called before render method()

getDerivedStateFromProps(props,state):

  • this method is called before rendering and allow us to update component’s state based on the changes in props.

render():

  • this method is responsible for generating the React elements to be displayed on the screen.
  • It is mandatory and called each time the component is rendered.

componentDidMount():

  • This method runs after the component output has been rendered to the DOM
  • This method runs after render method in class component.

UpdatingPhase:

getDerivedStateFromProps(nextProps,preState):

  • this method is also called before rendering and allow us to update component’s state based on the changes in props.

shouldComponentUpdate(nextProps,nextState):

  • a

getSnapshotBeforeUpdate(prevProps, prevState):

  • This method is called right before changes from the Virtual DOM are flushed to the actual DOM.
  • It is rarely used but can be helpful when you need to capture some information from the DOM before it changes.

componentDidMount():

  • This method runs after the component output has been rendered to the DOM
  • This method runs after render method in class component.

componentDidUpdate():

  • This method invokes when there is changes in state or props.

componentWillUnmount.

  • This method is called just before the component is unmounted and destroyed.
  • Usualy used to perform cleanups.

getDerivedStateFromError(error);

componentDidCatch(error, info);

Hooks:

  • Hooks are a feature in React that allow functional components to have state, lifecycle methods, and other React features without using class components.
  • Using hooks, we can use lifecycle methods in Functionl component.
  • Some Commonly used hooks are:
  1. useState: Allows functional components to manage local state.
  2. useEffect: Enables performing side effects like data fetching and subscriptions after rendering.
  3. useContext: Enables functional components to access data from a React context.
  4. useReducer: An alternative to useState for more complex state management.
  5. useMemo and useCallback: Optimize performance by memoizing expensive calculations and functions.

useMemo Hook:

  • if a function is called of every render, then we can memized their value and put a condition that it will call on a particular state change.
  • UseMemo accept two argument, first is memoized function and second is dependency list.
  • using useMemo Hook, we can remove unwanted calles, which can inhance performance.
  • useMemo hook accept a callback function and an array of state or props.
  • If mentioned props or state will update, then callback function will call.
  • useMemo is a React Hook that helps optimize functional components by memoizing expensive calculations.
  • It caches the result of a function and returns the cached value if the dependencies (specified as the second argument) remain unchanged between renders.
  • This avoids unnecessary re-computation of values, improving component performance.
  • useMemo is especially useful when dealing with large datasets, complex computations, or frequently updating components.
  • By using useMemo, we can ensure that the calculation is only performed when necessary, reducing the processing overhead and enhancing the responsiveness of our React application.

Ex:

import React, { useEffect, useState,useMemo } from “react”;

const Usememo = () => {

const [count,setCount] = useState(0);

const [item,setItem] = useState(1);

const multiplyval = useMemo(function multiply(){

console.log(‘in’)

return item*5;

},[item]);

return (

<div className=”Test”>

<h4>Test Usememo</h4>

<h2>Count : {count}</h2>

<h2>Item : {item}</h2>

<h2>Multiply : {multiplyval}</h2>

<button onClick={()=>setCount(count+1)}>Update Count</button>

<button onClick={()=>setItem(item*5)}>Update Item</button>

</div>

);

};

export default Usememo;

  • In the above example, console.log will call when on item state will update.

can we use useMemo in class component?

UseCallback();

  • If a function is return a function definition, then is this case we use useCallback hook instead of useMemo.

Ex:

  • useCallback(()=>{

return ()=>{};

},[])

Differences:

  • We use useMemo when you want to store and reuse the result of a computation, preventing unnecessary recalculations in subsequent renders
  • We use useCallback is used to memoize a function and prevent unnecessary re-creation of the function on every render.

UseEffect:

  • useEffect is a replacement for the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount used in class-based components.
  • useEffect is a built-in Hook that allows us to perform side effects in functional components.
  • Side effects typically include actions such as fetching data, subscribing to events, or manipulating the DOM.

Below are the example how to handle lifecycle methods:

  • ComponentDidMount=>

const [data, setData] = useState([]);

useEffect(() => {

// Fetch data from the API

fetch(‘https://api.example.com/data’)

.then((response) => response.json())

.then((data) => setData(data))

.catch((error) => console.error(error));

}, []);

  • If the dependencies array is empty, the effect will run only once after the initial render, similar to componentDidMount.
  • ComponentDidUpdate=>

const [data, setData] = useState([]);

useEffect(() => {

// Fetch data from the API

fetch(‘https://api.example.com/data’)

.then((response) => response.json())

.then((data) => setData(data))

.catch((error) => console.error(error));

}, [data1,data2]);

  • on change of data1 or data2, useEffect will be call.
  • ComponentWillUnmount=>

import React, { useEffect } from ‘react’;

function ExampleComponent() {

useEffect(() => {

// Cleanup function (equivalent to componentWillUnmount)

return () => {

console.log(‘Component will unmount (cleanup).’);

// Perform cleanup tasks here (e.g., canceling timers, removing event listeners).

};

}, []);

}

  • useEffect Hook allows us to return a cleanup function, which will be executed when the component is unmounted.

UseReducer

  • this is a hook which is helpful when large number of state is managed.
  • useReducer provides an alternative way to manage complex state logic in functional components.
  • It is an alternative to using useState when the state transitions involve complex actions or are dependent on the previous state.
  • useReducer Hook takes a reducer function and an initial state as arguments and returns the current state and a dispatch function
  • import React, { useReducer } from ‘react’;

// Reducer function takes the current state and an action, and returns the new state

const reducer = (state, action) => {

switch (action.type) {

case ‘INCREMENT’:

return { …state, count: state.count + 1 };

case ‘DECREMENT’:

return { …state, count: state.count – 1 };

default:

return state;

}

};

function CounterComponent() {

// Initial state

const initialState = { count: 0 };

// useReducer returns the current state and a dispatch function to update the state

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

return (

<div>

<p>Count: {state.count}</p>

<button onClick={() => dispatch({ type: ‘INCREMENT’ })}>Increment</button>

<button onClick={() => dispatch({ type: ‘DECREMENT’ })}>Decrement</button>

</div>

);

}

  • In above example, we have defined a reducer function that takes the current state and an action and returns the new state based on the action type.
  • The useReducer Hook manages the state transitions based on the dispatched actions.
  • useReducer is particularly useful when the state management logic becomes more complex or when multiple actions need to modify the state in a predictable way.

useContext Hook:

  • useContext allows functional components to consume data from a context created using the React.createContext method.
  • It provides a way to pass data down the component tree without the need for prop drilling.
  • This make easier to share data among multiple components.

how useContext works:

1) Create a context using React.createContext:

import React from ‘react’;

// Create a context with an initial value

const MyContext = React.createContext(initialValue);

2)Wrap the component tree with the context provider:

import React from ‘react’;

import { MyContext } from ‘./MyContext’;

function App() {

return (

<MyContext.Provider value={data}>

{/* Your component tree goes here */}

</MyContext.Provider>

);

}

3)Consume the context value in child components using useContext:

import React, { useContext } from ‘react’;

import { MyContext } from ‘./MyContext’;

function ChildComponent() {

// Consume the context value using useContext

const contextData = useContext(MyContext);

return (

<div>

<p>Data from Context: {contextData}</p>

</div>

);

}

  • useContext hook should be used when you need to access data from the context directly within the functional component.
  • If you only need to pass data down to child components without consuming it in the current component, using the context provider and consumer pattern with MyContext.Consumer might be more appropriate.

Custome Hook:

  • A custom hook is a function that allows us to reuse logic across multiple components.
  • To create a custom hook, you simply define a function that uses built-in React hooks or other custom hooks inside it.
  • Custom hooks always start with the word “use” to follow the React hook naming convention.

Redux:

  • Redux is a state management library.
  • It provides a centralized store to manage the state of an application.
  • Making it easier to maintain and update the state across different components.

Key concepts in Redux:

  • Store: A single source of truth that holds the entire application state in a plain object.
  • Actions: Plain JavaScript objects that describe what happened in the application.
  • They are dispatched to the Redux store to trigger state changes.
  • Reducers: Pure functions that specify how the application’s state changes in response to actions.
  • They take the previous state and an action as input and return a new state.
  • Dispatch: A method used to send actions to the Redux store, triggering state updates.
  • Subscribe: A method to add listeners to the Redux store, which are called whenever the state changes.

** React-Redux is a library that integrates Redux with React

npm install redux react-redux

useRef:

  • useRef hook is used to create a mutable reference that persists across re-renders of a functional component.
  • Unlike useState, updating the useRef does not trigger a re-render.
  • It’s commonly used to access or modify DOM elements
  • import React, { useRef } from ‘react’;

function ExampleComponent() {

// Create a useRef to store a reference to an input element

const inputRef = useRef(null);

const handleButtonClick = () => {

// Access the value of the input element using the .current property of the ref

const inputValue = inputRef.current.value;

alert(`Input value: ${inputValue}`);

};

return (

<div>

<input ref={inputRef} type=”text” />

<button onClick={handleButtonClick}>Get Input Value</button>

</div>

);

}

  • In this example, we create a useRef called inputRef and attach it to the input element using the ref attribute.
  • When the button is clicked, the handleButtonClick function reads the value of the input element.
  • modifying the current property of a useRef doesn’t trigger a re-render,
  • If we need to re-render the component based on some changes, use useState or other state management hooks instead.

Unit Testing

Await

Async

Promise