Destructuring in JavaScript:
Javascript desctructuring it is the way to extracting or unpacking values from an object or
array property and assigning them to a varible. By default, the object key name becomes the
variable that holds the respective value.
The destructuring is also possible for javascript arrays.
let person = {
name:"atul",
age:21,
gender:"male"
};
Const {name:name1, age:age1} = person;
in const variable name refers to object key and name1 refres to variable. Where we will destructure
that particular object key
let arr = [1,2,3,4,5];
console.log(arr);
let [one, two, three, four, five] = arr;
console.log(two);
//nested array
let arr2=[1,2,3,{"atul","shubham"}];
let [one two.{name1, name2}] = arr2;
in array destructuring variable names referes two each array values respectively.
Ex.in above array DE structuring one refers to first array value.two refers to second array value.and so
on.
JavaScript modules
A module in JavaScript a file containing related code or chunk of code.
In JavaScript we use import and export keywords to share and receive code respectively.
Which means instead of having all code in same file we can break code into different files and we can
use anywhere we want with the help of export and import keyword.
Note: we need to mention type=” module” inside a script tag. And src attribute. There src attribute
we need to mention imported module in JavaScript file.
There are two types of modules.
1.name module
2.default module
Ex.default export:
function msg(){
console.log("Hii atul biradar");
export default msg;
import msg from "./file2.js";
=====
function msg1(){
console.log("Hii atul biradar");
function msg2(){
console.log("hii shubham patil");
let emp = {
name:"atul",
age:21
export {msg1, msg2, emp};
import * as file2 from "./file2.js"; // we can import more than one component.
file2.msg1();
file2.msg2();
console.log(file2.emp);
ex.named export:
export function add() {
console.log("Good moring");
export function sub(){
console.log("good evening");
import {add} from "./file2.js";
import {sub} from "./file2.js";
add();
sub();
Multi page Application or website
request
AMAZON.in Server
• loads new page each time user performs specific action, which can make them good choice
for ecommerce development projects that need to display a wide range of products and
services.
• Mpa also excel at SEO optimization, scalability, and providing analytics insights. However,
Mpas can have slower output times because they need to request data from each page.
Single page application:
• Load everything from a single page, which can result in fast loading times and seamless user
experience.
• SPAs can be more vulnerable to security attacks, and they may have navigation issues like
unexpected back button behavior.
• SPAs also require JavaScript to function and may have poor SEO support.
React
React is a JavaScript library which is used to create single page application.
Library
It is a pre-written code that developers can use to speed-up software.
Framework
Collection of small libraries.
Features of React
1) It is component-based library.
2) It is declarative in nature.
3) It is use one way data binding. (parent to child)
4) It uses JSX to write code.
5) It uses virtual DOM.
Advantages of React
1. Ui development time is reduce performance of website will improve.
2. Network load will reduce.
3. File size of project is reduce.
Disadvantages of React
1. Initial load time of project is more.
2. React projects are less comparable with SEO (Search engine optimization)
Why react is so popular
• It is easy to learn.
• High performance.
• Reusable component (Code).
• Strong community support.
• Code stability.
Real Dom
HTML
Head body
H1
link
meta
Virtual DOM:
React maintain a light weight representation of the real dom heap memory is known as virtual dom.
This virtual Dom is JavaScript pre-structured of ui component.
Whenever we will update the code first it will update in reference representation of virtual dom.
If changes then update in virtual dom then automatically change in real dom.
Reconciliation In react:
It refers to the process efficiently updating the actual dom to reflect changes made to the virtual.
It is core concept that contribute react performance optimization.
Diffing Algorithm
React deploys a highly efficient diffing algorithm to compare the virtual dom tree structure with the
new virtual dom tree this algorithm identifies the minimal set of changes that need to be made real
dom to bring it sync with the new virtual dom.
Patching
Instead of changing multiple updates the react will patch them in single operation this will cause
resulting in improved performance.
Installation of React
There are many ways to install react in your system will see 2 best ways to install react project.
But before installing react you should have node js in your system so download node and check the
version of node by using command node -v.
First way by using CLI create-react-app
To install react, you can use the create-react-app utility to set up the tools needed for a react
application. Here are some steps.
Create a new project folder. For example, mkdir ReactProject.
Enter the directory of the new project folder. For Example, cd ReactProject.
Run the command npx create-react-app [project name(my-react-app)]. The installation process may
take a few minutes.
Change the directories into the new app. For Example, cd my-react-app.
Install dependencies. For example, npm install.
Start the local development server. For example, npm start. This command will open a new browser
window displaying the app.
Second way to install react by using vite
Here are the steps to install react with Vite (Module bundler)
Install Node.js and Create a new Vite Project.
Open your terminal type npm create vite@latest and press enter
Name your project for example, myReact
Select React as your framework and select language as javaScript.
Navigate to the project directory.
Install dependencies: Type npm install and press enter
Run the development server: type npm run dev and press enter
Useful way to use props as children:
Whenever you need to pass use full prop which means only one child component we will pass and
data we will change each time whenever we are passing or calling that prop inside parent
component.
The main use of passing use full props inside the parent component we can create the card or
whatever css structure we want by creating that porp calling statement in such way like HTML tag.
Child component
import React from 'react'
const UsefulProp = ({children}) => {
let style={
boxShadow:"0 0 3px 5px gray",
border : "2px solid black",
padding: "2px",
borderRadius: "5px "
return (
<div>
<p style={style}>{children}</p>
</div>
export default UsefulProp
Parent component
Import React from ‘react’
Import Usefullprops from ‘./UsefullProps.jsx’;
Const App =()=>{
return(
<div>
<Usefullporps>
<img src=https://www.imgae1.com alt=””>
<h1>Image one</h1>
<Usefullporps/>
<Usefullporps>
<img src=https://www.imgae1.com alt=””>
<h1>Image one</h1>
<Usefullporps/>
);
Export default app;
CSS file for usefullporps for children component
Let style = {
boxShadow:"0 0 3px 5px gray",
border : "2px solid black",
padding: "2px",
borderRadius: "5px"
State in react:
React component have built-in state object. The state object is where we store property
values that belongs to the component when the state object changes, the component re-renders.
What is state
The state is an instance of react component class. It can be defined as an object of a set of
observable properties that control the behavior of the component. In other words, the state of a
component is an object that holds some information that may change over the lifetime of the
component.
The state can be summarized as follows:
The state is a built-in react object that is used to contain data or information about the
component.
A component’s state can change over time, whenever it changes, the component re renders.
setState method in class components
setState() enqueues changes to the component state and tells react that this component and
its children need to be re-rendered with the updated state.
This is the primary method you use to update the user interface in response to event
handlers and server responses.
Use of setState
State can be updated in response to event handlers,server responses, or prop changes. This
is done using the setState() method.
Always use the setState() method to change the state object, since it will ensure that the
component knows it’s been updated and cells the render() method.
What are react hooks
React hooks are simple JavaScript functions that we can use to isolate the reusable part from
the functional component. Hooks can be stateful and can manage side effects. React provides a
bunch of standard in-built hooks.
useState Hook
The react useState Hook allows us to track state in a function component.
They let you use state and other react features without writing a class.
Usage of useState Hook
• Adding state to a component
• Updating state based on the previous state
• Updating objects and arrays in state
• Avoiding recreating the initial state
• Resetting state with a key
• Storing information from previous rendres
useState syntax
const [state, setState] = useState(initialstate);
call useState at the top level of the component to declare a state variable.
Parameters
• initialState: The value you want the state to be initially. It can bee a value of any type. But
there is a special behavior for functions. This argument is ignored after the initial render.
• If you pass a function as intialState, it will be treated as an initializer function. It should be
pure, should take no arguments, and should return a value of any type. React will call your
initializer function when initializing the component, and store its return value as the initial
state.
Returns
useState returns an array with exactly two values:
• The current state. During the first render, it will match the initalState you have passed.
• The set function that lets you update the state to a different value and trigger a re-render.
Synthetic Events
The react event handling system is known as synthetic events. The synthetic event is a cross-browser
wrapper of the browser’s native event. Handling events with react have some synthetic differences
from handling events on DOM. These are: react event are named as camelCase instead of lowercase.
NOTE: handling events with react elements is very similar to handling events in DOM elements
Binding event Handler
The different ways to bind event handlers are:
1) Binding inside the container
2) Binding by passing arrow function inside event listener
3) Binding directly when passing the function
4) Binding with the help of arrow function
5) Use functional component with arrow function
Note: in react if we use parenthesis for function while calling it on an event it will automatically give
the output but no output will be shown on firing the event.
Note: in class-based component using “()” will cause multiple re-renders which is not good.
import React from 'react'
import { useState } from "react";
const Counter = () => {
let [count, setCount]= useState(0)
let incCount = ()=> {
setCount(count + 1);
console.log(count);
return (
<div>
<h1>Count = {count}</h1>
<button onClick={incCount}>Increase Count</button>
</div>
export default Counter
Conditional Rendering
Conditional rendering term to describe the ability to render different user interface (UI) markup if a
condition is true or false. In react, it allows us to render different elements or components based on
a condition. This concept is applied often in the following scenarios:
• Rendering external data from an API.
• Showing or hiding elements.
• Toggling application functionality.
• Implementing permission level.
• Handling authentication and authorization.
The different ways of condition rendering are as follows.
Using If-else statement
An if-else statement will execute the action contained in the if block when the condition is satisfied.
Otherwise, it will execute the action contained in the else block.
import React from 'react'
const IfElse = () => {
let order = "iphone16";
if(order == "iphone16"){
return <h1>{order} is placed</h1>;
}else{
return <h1>{order} is UnAvailable</h1>
export default IfElse
Using switch statement
It would be more practical to apply the switch statement method when there are more than two
possible values or outcomes.
returing null from a component will cause it to hide itself (display nothing). This a good way to good
way to toggle the visibility of component.
import React from 'react'
const Switch = ({fruit}) => {
switch (fruit) {
case "Apple":
return (
<div>
<h1>Apple is Available & Order is placed!!</h1>
<img
src="https://static.vecteezy.com/system/resources/thumbnails/016/940/260/small/apple
-fruit-isolated-on-white-background-photo.jpg"
alt=""
height={250}
width={350}
/>
</div>
case "Banana" :
return (
<div>
<h1>Banana is Available & Order is placed!!</h1>
<img
src="https://www.shutterstock.com/image-photo/bunch-bananas-isolated-on-white-
260nw-1722111529.jpg"
alt=""
height={250}
width={350}
/>
</div>
case "Mango" :
return (
<div>
<h1>Mango is Available & Order is placed!!</h1>
<img
src="https://devgadmango.com/wp-content/uploads/2019/11/orignal-mango.png"
alt=""
height={250}
width={350}
/>
</div>
default:
return <h1>Fruit is not Available</h1>
export default Switch
Using Ternary Operator
The ternary operator approach is useful for uncomplicated if…else evaluation. For complicated
comparisons and components, it may impact readability as a project grows.
import React, { useState } from 'react'
const Ternaryoperator = () => {
let [food, setFood] = useState("IDLY");
return (
<div>
{food == "IDLY" ? <h3>IDLY is available & ordered</h3> : <h3>IDLY is not available!!</h3>}
</div>
export default Ternaryoperator
One more example for ternary operator
import React, { useState } from 'react'
const ChooseFood = () => {
let [food, setFood] = useState(" ");
return (
<div>
<section>
{food !==" "? <h3>{food} is Available & ordered</h3> : <h3>choose food</h3>}
</section>
<button onClick={()=>{setFood("IDLY")}}>IDLY</button>
<button onClick={()=>{setFood("DOSA")}}>DOSA</button>
</div>
export default ChooseFood
using Logical && (Short Circuit Evaluation)
Short circuit evaluation is technique to ensure that there are no side effect during the evaluation of
operands in an expression.
The logical && helps specify that an action should be taken only on one condition otherwise it could
be ignored.
import React, { useState } from 'react'
const AccessObject2 = () => {
let [data, setData] = useState(0); ------ uI will not Break
let [data, setData] = useState(null); ---------- uI will not Break
let [data, setData] = useState(undefined); ------ uI will not Break
let [data, setData] = useState(""); -------- uI will Break
return (
<div>
<section>
{data &&
data?.map(ele=>{
return(
<li>
Name: {ele.name}, Age: {ele.age}
</li>
)
})}
</section>
</div>
export default AccessObject2
Fragments
React fragment is a feature in react that allows you to return multiple elements from a react
component by allowing you to group a list of children without adding extra nodes to the DOM.
To return multiple elements from a react component, you will need to wrap the elements in a root
element.
Short syntax for react fragments
The short syntax for react fragments looks like empty tags
<> </>
We can use it the same way as any other element except that it does not support keys and attributes.
Keyed Fragments
Fragments declared with the explicit <Fragment> Syntax may have keys. A use case for this is
mapping a collection to an array of fragments.
<Fragment key={id}>
<ul>
<li></li>
</ul>
<Fragment/>
Keys
Keys helps react identify which items have changed, are added, or are removed. Keys should be given
to the elements inside the array to give the elements a stable identity.
It also helps to determine which components in a collection needs to be re-rendered instead of re-
rendering the entire set of components every time.
Ref
Refs provide way to access DOM nodes or React elements created in the render method.
In the typical react dataflow, props are the only way that parent components interact with their
children. To modify a child, you re-render it with new props.
However, there are a few cases where you need to imperatively modify a child outside of the typical
dataflow. The child to be modified could be an instance of a react component, to it could be a DOM
element, for both of these cases, react provides an escape hatch.
When to use ref
• Managing focus, text selection, or media playback
• Triggering imperative animations.
• Integrating with third-party DOM libraries.
Note: Avoid using refs for anything that can be done declarative. Hence, don’t overuse refs.
Creating Refs:
Refs are creating using via the ref attribute. Refs are commonly assigned to an instance property
when a component is constructed so they can be reference throughout the component.
Accessing Ref:
When a ref is passed to an element in render, a reference to the node becomes accessible at the
current attribute of the ref.
import React, { useRef } from 'react'
const UseRef1 = () => {
let myH1 = useRef();
let changeColor = ()=>{
console.log(myH1);
myH1.current.style.color = 'green';
return (
<div>
<h1 ref={myH1} >Hello React useRef Hook</h1>
<button onClick={changeColor}>Change Color!!</button>
</div>
export default UseRef1
What is useRef?
The useRef Hook allows you to persist values between renders. It can be used to store a mutable
value that does not cause a re-render when updated. It can be used to access a DOM element
directly.
Practical application of Refs.
1. Animations.
2. Forms handling
3. Audio and video handling
4. Third party libraries