0% found this document useful (0 votes)
4 views36 pages

React

The document provides an overview of React, including its transition from Create React App to Vite for project creation, and explains key concepts such as Single-Page Applications (SPAs), components, state management, and the Virtual DOM. It highlights the benefits of using React, such as its declarative nature and component-based architecture, and discusses the differences between real and virtual DOMs. Additionally, it covers JSX syntax, props, and event handling in React applications.

Uploaded by

megatronled
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

React

The document provides an overview of React, including its transition from Create React App to Vite for project creation, and explains key concepts such as Single-Page Applications (SPAs), components, state management, and the Virtual DOM. It highlights the benefits of using React, such as its declarative nature and component-based architecture, and discusses the differences between real and virtual DOMs. Additionally, it covers JSX syntax, props, and event handling in React applications.

Uploaded by

megatronled
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In the videos, the command npx create-react-app was used to create the project.

However, this
method is deprecated in React 19. Instead, we now use Vite with the command npm create
vite@latest my-react-app --template react. Also, note that in Create React App, the entry file is
[Link], whereas in Vite, it is [Link]. npm run dev : to start app

What is React?
--------------
[Link] is a JavaScript Library developed by Facebook for building fast and interactive user
interfaces primarily for single-page applications(SPAs). It helps in building UI Components that
can manage their own state and can be composed into complex UI

[Link]: A Library is a collection of functions, utilities, or classes that we can call and use in
our application to perform specific tasks.

functions
---------
function add(a,b){
var c=a+b;
return c;
}
function mul(a,b){
var c=a*b;
return c;
}
function div(a,b){
var c=a/b;
return c;
}

add(10,20);

Collection of functions
-----------------------
[Link] and [Link]

Difference between Functions and Utilities


------------------------------------------
Functions: Any block of code that performs a specific task.

Utilities: A subset of functions that handle small, repeated, generic tasks.


NOTE
----
Subset means utilities are part of the larger group of functions, but they focus on a specific type
of task. So utilities are still functions.

All the functions together make up the library.

The utility functions (add, subtract, multiply, divide etc.) are a subset of the entire collections of
functions because they serve specific, simplet tasks that are generally resuable across many
applications.

React JS : Functions not Classes

Angular : Class based

Classes
-------
[Link] and [Link]

Alice is created account in our application

facebook : users

React (js or ts)

What is Single-Page Application (SPA)?


--------------------------------------
A Single-Page Application (SPA) is a web application or website that loads a single HTML Page
and dynamically updates the content on that page as the user interacts with the app. Instead of
loading new pages from the server for each interaction. SPAs dynamically rewrite the current
page, meaning the page doesn't refresh or reload as often. This results in a faster and smoother
user experience.

How SPAs Work:


--------------
Initial Load:
-------------
When the user first visits a SPA, the browser loads basic HTML, CSS, and Javascript files.
These files typically contain the entire structure and logic of the app.

Dynamic Updates:
---------------
After the initial load, when users interact with app (click on links, submit forms, etc...), only the
necessary data is fetched from server, and Javascript dynamically updates the content on the
page without refreshing the entire page.

Benefits of SPAs
----------------
Speed: Since only parts of the page are reloaded, SPAs feel faster and more responsive.

Smoother user experience: users don't experience full-page reload, so transition between
different sections of the app are seamless (Moving from one part of the app to another happens
quickly and without any visual disruption, such as flicketing or reloading the page)

Reduced Server Load : Once the SPA is loaded, only data (not full html pages) is requested
from the server.

Real-World SPA examples


-----------------------
Gmail
Google Map
Facebook

UI Components that manage their own state


-----------------------------------------
In React, a component is a reusable, self-contained piece of the User Interface(UI). It's the
building block of any React Application. Components let us split the UI into the independent,
reusable parts, and think about each part in isolation that is responsible part of the UI and
managing its own state.

In this context of React, "rendering" refers to the process of converting the react component's
JSX code into the actual HTML elements that can be display in the web browser.

Initial Rendering : This happens when the React component is first loaded onto the page. React
translates the component's JSX into real HTML and inserts it into the Browser's DOM.

function Welcome(){
return <h1>Hello, World!</h1>;
}

The Welcome component renders the JSX <h1>Hello World!</h1>

JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows us to wrtie
HTML-like code within Javascript, making it easier to describe the structure and layout of UI
components
For example, instead of using traditional javascript [Link]() calls, we can use JSX
like this:

JSX : Javascript and XML


------------------------
const element=<h1>Hello World!</h1>;

Javascript
----------
const element=[Link]("h1",null,"Hello World");
const element=[Link](
"h1",
{
className:"header",
id:"main-title",
onClick:()=>alert("Heading Clicked)
},
"Hello World");

HTML
----
<h1>Hello World!</h1>

State
-----
State refers to the data that a component can hold, which can change over time. React
components can manage this state internally and update themselves when the state changes.
JS
--
var count=0; // variable or state

var setCount=20;

count=20

React
-----
const [count, setCount]=useState(0)

import React, {useState} from "react";


function Counter(){
//state : "count" holds the current count value, "setCount" is used to update it
const [count, setCount]=useState(0);
return(
<div>
<p>You clicked {count}</p>
<button onClick={()=>setCount(count+1)}>Click me</button>
</div>
)
}
export default Counter;

count=0
count+1=0+1=1
count=1
count+1=1+1=2
count=2
count+1=2+1=3
.....
Explaination
------------
The Counter component has a piece of state called count, which starts with 0.

Each time the button is clicked, the setCount function updates the state by increasing count by
1.

The Component re-renders and updates the displayed count every time the state changes

This shows how react allows UI components to manage their own state and update themselves
automatically without needing to reload the entire page.

Re-rendering : This occurs when the component's state or props change. React re-calculates
what the UI should look like and only update the necessary parts of the DOM (not the entire
page).

Components Composed into Complex UIs


------------------------------------
Composition in react means that we can combine smaller components into a larger, more
complex UI. Instead of having a single large component, we can break our UI into small,
independent, reusable components. These components can be nested or combined to build
more complex user interfaces.

Why React?
----------
Declarative: React allows us to describe how the Ui should look at any point in time and updates
automatically when the underlying data changes.

Component-based : We build encapsulated (each component is self-contained and


independent, meaning it manages its own behavior, state, and appearance without affecting
other parts of the application). components that manage their own state, and then compose
them to make complex UIs.

Learn Once, Write Anywhere: React can be used for Web, Mobile (via React native), Desktop
Application (Visual Studio Code, Slack), Virtual Reality, Artificial Intelligence (AI) and Machine
Learning(ML) interfaces, Gaming, IoT(Internet of Things), Augmented Reality (AR) and more.

React History
-------------
Initial Release: May 29, 2013 (11 Years ag0)
Stable Release : 18.3.1 (April 26, 2024, 5 Months ago)
Original Author: Jordan Walke (Facebook Software Engineer)

HTML DOM Vs JavaScript DOM (Document Object Model)


----------------------------------------------------
HTML DOM: The structure of the webpage

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<p>This is paragraph</p>
</body>
</html>

JavaScript DOM: The interface used by javascript to manipulate that structure.

<!DOCTYPE html>
<html>

<head>
<title>HTML DOM</title>
</head>

<body>
<h1 id="title">Hello, World!</h1>
<p>This is paragraph</p>
<button onClick="changeTitle()">Change Title</button>
<script>
function changeTitle() {
[Link]("title").innerHTML="Updated Title";
}
</script>
</body>

</html>

HTML DOM example with Multiple Elements


---------------------------------------

Real (HTML / JS) DOM


--------------------

Real Book --> Open the book and Update --> Real book update is completed --> Real Book
--> Open the book and Update --> Real book update is completed --> Real Book

Virtual Book --> Instead of doing changes in Real book we will do changes in photocopy(Virual
Book) of that book and we will compare Real and photocopy --> Update changes in the Real
Book

<!DOCTYPE html>
<html>

<head>
<title>HTML DOM</title>
</head>

<body>
<h1 id="title">Hello, World!</h1>
<p id="paragraph">This is paragraph</p>
<button onClick="changeTitle()">Click Me to Update All</button>
<script>
function changeTitle() {
[Link]("title").textContent="This title has been updated";
[Link]("paragraph").textContent="This paragraph has been
updated";
}
</script>
</body>

</html>

How It Works:
-------------
Clicking the "Click Me to Update All" button triggers the changeTitle function
we update : The <h1> and <p> element

What happens in Real DOM


------------------------
Direct Manipulation: For every element we update, the browser has to re-render (refers to the
process where the browser updates the visual representation (content, or styles) of the
webpage) the DOM to reflect the changes.

Each time the textContent of an element is updated, the browser must:


--------------------------------------------------------------------
Recalculate the layout (reflow): The browser figures out how the content affects the layout of the
page.
Repaint : The browser then re-renders those parts of the web page.

If this page had hundreds or thousands of elements, updating them all directly in the real DOM
would be slow because each update forces the browser to go through this cycle of reflow and
repaint.

Virtual DOM
-----------
The updateContent function updates the state variables (greeting, paragraph) when we click the
button.

When we update the state in react:


----------------------------------
[Link] Virtual DOM is updated first.
[Link] then compares the new Virtual DOM with the previous Virtual DOM using a process
called Diffing.
[Link] only updates those parts of the real DOM that have changes, instead of re-rendering
the entire DOM.

import React, { useState } from "react";


function App() {
//State variables for different parts of the content
const [greeting, setGreeting] = useState("Hello!");
const [paragraph, setParagraph] = useState("This is paragraph");
const updateContent = () => {
setGreeting("Hello, World!");
setParagraph("This paragraph has been updated");
};
return (
<div>
<h1>{greeting}</h1>
<p>{paragraph}</p>
<button onClick={updateContent}>Click Me to Update All</button>
</div>
);
}
export default App;

old Virtual DOM


<h1>Hello, World!</h1>
<p>This is paragraph</p>

new Virtual DOM


<h1>Hello, World!</h1>
<p>This paragraph has been updated</p>

Difference between Real DOM and Virtual DOM


-------------------------------------------
Feature : Update
----------------
Real DOM : Method Direcly manipulates the real DOM for each element.
Virtual DOM : Updates the Virtual DOM and then applies minimal changes to the Real DOM

Feature : Efficiency
--------------------
Real DOM : Each changes causes a reflow and repaint in the real DOM, even for minor updates
Virtual DOM : React performs a diffing to determine the minimal real DOM updates. Only for
necessary elements are re-rendered.

Feature : Performance Impact


--------------------
Real DOM : Frequent updates can cause performance degradation, especially with many
elements.
Virtual DOM : More Efficient because only the changes parts of the DOM are updated, reducing
the number of reflows and repaints.

Feature : Re-rendering
----------------------
Real DOM : All changes happen immediately in the real DOM, which can lead to unnecessary
re-rendering
Virtual DOM : Only the differences between the old and new Virtual DOm are applied to the real
DOM

Feature : use Case


--------------------
Real DOM : Suitable for simple or small pages with fewer Dynamic updates.
Virtual DOM : Ideal for complex or dynamic webpages where Frequent update occurs.

[Link] was first used in 2011 for Facebook's Newsfeed feature (Like, Post, Comment....)

npx and npm are both command-line tools that come with [Link] and are part of the npm
(Node Package Manager) ecosystem

UI ecosystem : css frameworks and js libraries and frameworks

npm install bootstrap

node package manager (npm) is mainly used for installing modules or packages and managing
project dependencies

npx is primarily used to execute npm packages

npx create-react-app projectname


cd projectname
npm start

Project structure: After creating the project. we will have below structure

projectname
-node_modules
-public
-[Link]
-src
-[Link] //Main(root) Component
-[Link] //Entry point
-[Link]

Browser --> localhost:3000 --> public/[Link] --> <div id="root"></div>

[Link]
--------
import React from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';
import App from './App';
import reportWebVitals from './reportWebVitals';

[Link]([Link]('root')).render(
<[Link]>
<App />
</[Link]>
);

Flow of execution
-----------------
[Link]().render() : This function tells React where to render the React
app(inside the <div id="root">ddfgdfgfd</div> element in public/[Link])
App Component: The <App /> component, imported from [Link], is the root component of the
[Link] will be rendered inside the <div id="root"></div>

Browser --> localhost:3000 --> public/[Link] --> <div id="root">[Link]</div>

JSX

Components

Simple Project based on bootstrap


---------------------------------
jsx
routing

jsx
---
[Link] stands for JavaScript XML
[Link] allows us to write HTML in react
[Link] makes it easier to write and add HTML in react.

Expressions in JSX
------------------
with JSX we can write expressions inside curly braces { }

The expression can be a react variable or property or any other valid javascript expression.
JSX will execute the expression and return the result.

Inserting a large block of html


-------------------------------

One Top Level Element


----------------------
The HTML code must be wrapped in one top level element

React : XHTML
-------------
<hr>, <br>, <img>, <input type="text"> : HTML and ANGULAR
<hr/>, <br/>, <img/>, <input type="text"/> : XHTML and REACT

React : class
-------------
<h1 className="sample"></h1>
<h1 class="sample"></h1>
<h1 id=""></h1>

Conditions
----------

ternary operator (?)


----------------
condition?"true":"false"

Rendering a List
----------------
map()
Rendering Multiple Components
-----------------------------

Handling Events in JSX


----------------------

Inline Styles in JSX


--------------------

Fragments to Avoid extra wrapping element


-----------------------------------------
if we want to avoud adding unnecessary div elements, use React Fragments <> </> : empty tag

Components
----------
Components are like functions that return HTML elements

React Components are independent and resuable bits of code. They serve same as javascript
functions, but work in isolation and return HTML

Components come in two types


----------------------------
[Link] component
[Link] Component (outdated)
----------------------------
In older react code bases, we may find Class Components primarily used. It is now suggested
to use Function components along with Hooks(works with function components), which were
added in react 16.8

Props
-----
Components can be passed as props, which stands for properties.

Props are like function arguments, and we send them into component as attributes.

JS Functions : function App(props)


HTML : <p color="red">

Components in Components
------------------------
We can refer to components inside other components

Components in Files
-------------------

Props (properties)
------------------
Props are arguments passed into react components.

Props are passed into components via HTML attributes

Pass Data
---------
Props are also how we pass data from one component to another component, as parameters

Variables
---------

Object
------

Mutliple props
--------------

Default Props
-------------

Events
------
Just like HTML DOM Events, React can perform actions based on user events.

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

Passing Arguments
-----------------
To pass an arguments to an even handler, use an arrow function

Event Object
------------
Event handlers have access to the React event that triggered the function.

Condional Rendering
-------------------
In React, we can conditionally render components

Difference between export and export default


--------------------------------------------
export default : Allows only one export per file and can be imported without curly braces. it's
ideal for the main export of a file

//[Link]
function App(){
return <h1>Hello World</h1>
}
export default App;

//[Link]
import App from "./App"

export (named export) : we can have multiple named exports per file and must import them
using the exact name with curly braces

//[Link]
export const add=(a,b)=>a+b;
export const subtract=(a,b)=>a-b;

import {add,subtract} from "./utilities";

React Router
------------
create-react-app doesn't include page routing

React Router is the most popular solution

Folder structure
----------------
src/pages/
----------
[Link]
[Link]
[Link]
[Link]
[Link]

We wrap our content first with <BrowserRouter>

The we define our <Routes>. An Application can have multiple <Routes>. Our basic example
only uses one.

<Route> s can be nested. The first <Route> has a path of / and renders the layout component.

The nested <Route> s inherit and add to the parent route. so the about path is combined with
parent and becomes /about

The Home component route doesn't have a path but has an index attribute. That specifies this
route as the default route for the parent route which is /

Setting the path to * will act as a catch-all for any undefined URLs. This is great for a 404 error
page.

The Layout Component has <Outlet> and <Link> elements

The <Outlet> renders the current route selected (Home, About, Contact, NoPage)

<Link> is used to set the URL and keep tract of browser histtory

Anytime we link to an internal path, we will use <Link> instead of <a href="">

The "layout route" is a shared component that inserts common content on all pages, such as a
navigation menu.

React CSS
---------
[Link] Styling
[Link] or CSS Stylesheets
[Link] Modules

[Link] Styling
----------------
In React, inline styling refers to adding css styles directly to elements via style attribute, similar
to inline styles in HTML but adapted to Javascript.

Advantages
----------
Scoped Styling : Styles are isolated to a specific element, preventing style conflicts
Dynamic Styles : We can easily apply conditional or dynamic styles based on component props
or state (pending)

Disadvantages
-------------
Limited CSS features: Inline styling doesn't support advanced CSS features like
pseudo-classes, pseudo elements, media queries, and animations.

Reduced Reusability : Styles are tied to individual elements, making it hard to reuse them
across components

css
---
background-color:red;

js
--
backgroundColor:red; (camelCase)

[Link] or CSS Stylesheets


-----------------------------
CSS stylesheets are External .css files imported into react components. They allow for
traditional css syntax and enable styles to be shared across multiple components

Advantages
----------
Reuse and Maintainability : CSS files allow reuse of classes across components and are easy
to manage.
FULL CSS support : we can use all CSS features like pseudo-classes, pseudo elements, media
queries, and animations.

Disadvantages
-------------
Global Scope : Styles are global, so class names can potentially clash and override each other
if not carefully named

CSS modules
-----------
CSS modules are CSS files in which class and animation names are scoped locally by default.
They are imported into components as objects (js), ensuring unique and collision-free styles

Advantages
----------
Local Scope: CSS modules generate unique class names preventing style conflicts

Maintainable and Modular: CSS modules provides modularity, making it easier to manage and
debug styles.

Disadvantages
-------------
Limited Dynamic Styling : Applying dynamic or conditional styles requires a bit a more setup
compared to inline styles.

React Hooks
-----------
Hooks were added to React in version 16.8

Hooks allow function components to have access to state (useSate) and other React features.

Because of this, class components are generally no longer needed.

NOTE: Although Hooks generally replace class components, there are no plans to remove
classes from react.

Hook rules
----------
[Link] can only be called inside the react function components
[Link] can only be called at the top level of a component.
[Link] cannot be conditional, inside loops or nested functions.
useState
--------
The react useState hook allows us to track a state in a function component.

State generally refers to data or properties that need to be tracking in an application.

import useState
---------------
import {useState} from "react"

var x=10
let x=10
const x=10

const [color,setColor]=useState("red");

useState accepts an initial state and returns two values

color : the current state (red)


setColor : A function that updates the state

The useState Hooks can be used to keep track of strings, numbers, booleans, arrays, objects
and any combination if these!

`` : backtiks (Template Literals)

import { useState } from "react";

function TextInput(){
//useState("") initializes text as an empty string and setText as the function to update it
const [text,setText]=useState("");
const handleTextChange=(e)=>{
setText([Link]);
}
return(
<>
<label>Text Input:</label>
{/* value={text} binds the input field to the text state, so any change reflects in the input
field */}
<input type="text" value={text} onChange={handleTextChange}/>
<p>{text}</p>
</>
)
}
export default TextInput;

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

Form Validation
---------------
The trim() method in javascript is used to removed any leading (spaces at the beginning) and
trailing(spaces at the end) whitespace characters from a string.

const input=" Hello World ";

const trimmedInput=[Link]();

[Link](trimmedInput); //Hello World

const input=" ";


[Link](input==="")//false

const input=" ";


[Link]([Link]()==="")//true

useEffect
---------
Mounting
--------
Mounting is the process where a react component is created and inserted into the DOM for the
first time.
ex
--
[Link]
------
function App() {
return (
<div>
<h1>Welcome to React</h1>
</div>
);
}

export default App;

[Link]
--------
import React from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = [Link]([Link]('root'));


[Link](
<[Link]>
<App />
</[Link]>
);

// If you want to start measuring performance in your app, pass a function


// to log results (for example: reportWebVitals([Link]))
// or send to an analytics endpoint. Learn more: [Link]
reportWebVitals();

NOTE :
------
[Link] we use <App/> for the first time in our [Link] file
[Link] App component mounts into the DOM

unmounting
----------
unmounting is the process where a react component is removed from the DOM

rendering
re-rendering

useEffect
---------
The useEffect hook in react used to handle side effects in functional components.

Side effects include such as:


-----------------------------
[Link] data from APIs
[Link] the DOM directly
[Link] up subscriptions or timers

NOTE
----
It replaces lifecycle methods like componentDidMount, componentDidUpdate, and
componentWillUnmount in class components.

syntax
------
useEffect(callback,dependencies);

NOTE: dependencies (optional): An array of values that the effect depends on. changes in the
values re-trigger the effect.

Behavior
---------
without dependencies : the effect runs after every render
with an empty dependency array : the effect runs only once, after the component mounts
with specific dependencies : the effect runs whenever the specified dependencies change.

Cleanup function
----------------
the callback can return a function for Cleanup. this Cleanup is executed before the next effect or
when the component unmounts

useEffect runs on every render. that means that when the count changes, a render happens,
which then triggers another effect

[Link] on Component Mount


----------------------------

[Link]-run Effect when dependencies change


----------------------------------------

[Link] data from API


------------------------
REST APIs : JSON (key-value pairs)
----------------
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit
molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
SOAP APIs : XML (outdated)
--------------------------
<userId>1</userId>
<id>1</id>
<title>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</title>
<body>quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit
molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto</body>

[Link]

map()

async
-----
The async keyword is used because this function will perform asynchronous operation
asynchronous operation in javascript is a process that allows the program to continue running
other tasks while waiting for an operation to complete. Instead of blocking the execution,
asynchronous operations run in the background and notify once they are done.

try{

}
catch

cors : Cross-Origin Resource Sharing

[Link] or [Link]

[Link]

axios
await fetch("[Link]

[Link]
[Link]

fetch is used to make a network requiest to the give API or Rest API or API endpoint

await pauses the execution of this function until promise returned by 'fetch' is resolved

A promise in javascript is an object representing the eventual completion or failure of an


asynchronous operation. it doesn't represent the actual result but rather a placeholder for the
future result of the operation.

await [Link]();

the .json() method parses the json body of the response.

'await' ensures the function waits untial the parsing is complete

parsing is the process if analyzing a piece of data (usually in text format) and converting into a
usable format.

response=await fetch("[Link]
const jsonData={
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit
molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
[Link](typeof jsonData); // string

parsing json
------------
const parsedData=[Link](jsonData);
[Link](typeof parsedData); // "object"
[Link]([Link]);

4. Listening to Window Resize


-----------------------------

Cleanup function
----------------
mount : add the component
unmount : remove the component

Why Do We Need a Cleanup Function in the code


---------------------------------------------
The Cleanup function is the useEffect hook is necessary to remove the resize event listener
when the component is unmounted or re-rendered. Without this Cleanup, the event listener
would remain attached to the window object, leading to protential issues such as:

[Link] memory leaks


-----------------------
Every time we add an event listener (e.g. [Link]), it consumes memory. If the
WindowSize component is unmounted (removed from the DOM), but the event listener remains
active, it will keep running and occupy memory unnecessarily.

The Cleanup function ensures that the event listener is removed when the component
unmounts, preventing memory leaks.

[Link] Unexpected behavior


--------------------------------
If the component is unmounted but the resize eventlistener still exists, it will attempt to call
handleResize, even though the component is no longer in use.

This can cause errors, such as:


Trying to update state (setWidth, setHeight) on an unmounted component
unnecessarily computations or re-renders

[Link] practice in react


------------------------
React encourages proper resource Cleanup in useEffect to ensure our application runs
Efficiently
Event Listeners, intervals, and subscriptions should always be removed whenever no longer
needed to avoid side effects.

[Link] without dependency array (runs on every render)


--------------------------------------------------------
In our NoDependency component, the useEffect hook is being used without a dependency
array:

useEffect(()=>{
[Link](`Input changed to: ${text}`);
});//No dependency array
What happpens here
------------------
without dependency array, the useEffect runs on every render, not just when text changes
Everyt time the components re-renders (e.g. due to state change), the useEffect hook will
execute.

Why this a problem:


-------------------
Performance issues :
--------------------
If the effect is performing heavy operations (e.g, making api calls, processing large data, or
interacting with DOM), it will significantly impact performance.

Running the effect unnecessarily on every render waster resources and can slow down the app.

Infinite loop (Potential risk)


------------------------------
If the useEffect modifies state (e.g. setText), it will cause re-render, triggering the useEffect
again, creating an infinite loop.

How to fix this


---------------
Add dependency array

[Link]
------------
React Context is a way to manage state globally

It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone

import React, { useState } from 'react';


import ReactDOM from 'react-dom/client';
import './[Link]';
import reportWebVitals from './reportWebVitals';

function Component1(){
const [user,setUser]=useState("Siva");
return(
<>
<h1>{`Hello ${user}`}</h1>
<Component2 user={user}/>
</>
)
}

function Component2({user}){
return(
<>
<h1>Component 2</h1>
<Component3 user={user}/>
</>
)
}

function Component3({user}){
return(
<>
<h1>Component 3</h1>
<Component4 user={user}/>
</>
)
}

function Component4({user}){
return(
<>
<h1>Component 4</h1>
<Component5 user={user}/>
</>
)
}

function Component5({user}){
return(
<>
<h1>Component 5</h1>
<h2>{`Hello ${user} again!`}</h2>
</>
)
}

const root = [Link]([Link]('root'));


[Link](
<[Link]>
<Component1 />
</[Link]>
);

// If you want to start measuring performance in your app, pass a function


// to log results (for example: reportWebVitals([Link]))
// or send to an analytics endpoint. Learn more: [Link]
reportWebVitals();

Even though components 2-4 did not need the state, they had to pass the state along so that it
could reach component 5

useState
useEffect
useContext

Custom Hooks
------------
Hooks are reusable functiions.

When we have component logic that needs to be used by multiple components, we can extract
that logic to a custom hook.

useReducer
----------
useReducer allows us to manage state using a reducer function.
A reducer is a function that takes the current state and an action, and returns a new state.

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

reducer : A function that determines the new state based on the current state and an action (A
pure function that calculates the next state based on the current state and the dispatched
action.).

Pure Function
-------------
The reducer function in useReducer is a pure function. It takes the current state and action as
arguments and returns a new state without mutating the original state or perform side effects.
mutable : not changeable
immutable : changeable

initialState : The starting value for our state

state : The current state

dispatch : A function to trigger state changes by sending an action.

When to use useReducer?


-----------------------
1. When we have complex state logic ( Works well when state management becomes complex
e.g., multiple fields in a form....)
2. When the state updated by multiple types of actions.
3. When the next state depends on the previous state.

1. Simple Counter

2. Managing Form State

Centralized Logic : keep all state transitions in one place


-----------------
function formReducer(state, action) {
switch ([Link]) {
case "updateField": return {
...state, [[Link]]: [Link]
};
case "reset": return {
name: "", email: ""
};
default: throw new Error("Unknown action");
}

axios
-----
Axios is a libray or module for making http requests

Axios
----
[Link] a simple and cleaner syntax
[Link] transforms json data
[Link] Built-in support for query parameters and request cancellations
[Link] throws an error for http response codes
404 File not Found
500
[Link] it easy to send files using FormData

Supports older browser like IE 11

Fetch
-----
[Link] into modern browsers, no additional library required
[Link] us to manually parse the JSON response using .json()
[Link] not throw an error http errors like 404 or 500. you need to handle those manually by
checking [Link]
[Link] Uploads are possible but require more code to handle FormData

Not supported in older browser like IE

CRUD
----
Create - Form
Read - Read
Update
Delete

API END POINTS


--------------
METHODS : post, get, put, delete
[Link] - post - Create
[Link] - get - Read
[Link] - put - Update
[Link] - delete - Delete

[Link]

API END POINTS


--------------
METHODS : post, get, put, delete
[Link] - post - Create
[Link] - get - Read
[Link] - put - Update
[Link] - delete - Delete

[Link]

API END POINTS


--------------
Registration: POST [Link] (name,email,password)
Login: POST [Link] (email, password)
Logout: POST [Link]

postman

!![Link]("authToken")
-----------------------------------
1. [Link]("authToken")
-------------------------------------
This retrieves the value associated with the key "authToken" from the browsers localStorage
if the key exists, it returns the stored value as a string
if the key doesn't exists , it returns null

2. ![Link]("authToken")
-------------------------------------
The logical NOT operator ! negates the value
if the value is null or an empty string "", it becomes true
if the value is a non-empty string, it becomes false.

3. !![Link]("authToken")
-------------------------------------
A second logical not operator is applied, flipping the value back to its original truithness.
This ensures the result is explicitly true or false, rather than the original value or null.

Pending
-------
useRef
------
The useRef hook allows us to persist values between renders.
It can be used to store mutable(changeable) value that doesnt cause a re-render when updated.

it can be used to access a DOM element directly.

Does not cause re-renders


-------------------------
If we tried to count how many times our application renders using the useState hook, we would
be caught in an infinite loop since this hook itself causes a re-render.

Tp avoid this, we can use the useRef Hook.

import { useEffect, useRef, useState } from 'react';

function App() {
const [inputValue, setInputValue] = useState("");
const count=useRef(0);
useEffect(()=>{
[Link]=[Link]+1;
})
return (
<div >
<input
type='text'
value={inputValue}
onChange={(e) => setInputValue([Link])}
/>
<h1>Render Count: {[Link]}</h1>
</div>
);
}

export default App;

useRef() only returns one item, it returns an Object called current.

when we initialize useRef we set the intial value : useRef(0).

Accessing DOM Elements


----------------------

Tracking state changes


----------------------

useCallback
------------
The react useCallback hook returns a memorized callback function

Think of memoization as caching a value so that it doesnot need to be recalculated

The useCallback hook only runs when one of its dependencies update.

This can improve performance

NOTE: One reason to use useCallback is to prevent from re-rendering unless it props have
changed.

useMemo
-------
The React useMemo hook returns a memoized value.

Sass: Syntactically Awesome Style Sheets


----------------------------------------
A CSS preprocessor (SASS / SCSS) is a program that lets us to generate css from the
preprocessor's own unique syntax.

SASS / SCSS
-----------
$clr: blue

SASS
----
body
color: $clr
h1
background-color: $clr

SCSS
----
$clr: blue
body{
color: $clr;
}

h1{
background-color: $clr;
}

ts

redux
-----
Redux is a predictable state management library widely used in JavaScript Applications,
particularly with React.
It helps manage the state of an application in a more organized and predictable manner,
especially in complex applications where state can become challenging to manage.

Ex:
---
What is Redux?
--------------
Redux is a tool that helps us to manage the data (or state) of our application in one central
place. Instead if keeping pieces of data across different components. Redux keeps it all in one
"box" called a store. This makes it easier to organize, update, and share data across our app.

How Does Redux Work?


--------------------
[Link]:
--------
Think of the store as a big box where all our app's data is kept. This box holds the current state
of our app.

[Link]:
----------
Actions are like notes we write to store saying. "Hey, something happened" for examople, an
action could say, "Add this item to the list" or "Remove the user"

[Link]
----------
Reducers are like instructions for the store. They explain how the store should change when an
action happens. For example, if the action says "Add this item", the reducer updates the list
inside the store.

[Link]
----------
Dispatch is how we send an action to the store.

ex : dispatch

[Link] Updates
----------------
when the store gets an action, it looks at the reducers and updates the state based on the
instructions, Once the state us updated, our app reacts and shows new data.

why use Redux?


--------------
Keeps things Organized: All our app's data is in one place.
Easy to Share data: Any part of our app can get data from the store, no matter where it is.
predictable: we always know how and why data is changing.

React Redux app


---------------
[Link] up redux (store, actions, reducer).
[Link] redux to react app.
[Link] actions to update the state.

File Structure
--------------
src
components
[Link]
redux
[Link]
[Link]
[Link]
[Link]
[Link]

Middleware and Redux-Thunk


--------------------------
Middleware in Redux is a way to extend or customize the behavior of redux. It sits in between
the action dispatch and reducer. Middleware can intercept actions, perform tasks(e,g., logging,
API calls) and pass actions to the reducers.

redux-Thunk
-----------
redux-thunk is a Middleware that allows action creators to return a function(instead of an
object). this function can contain asynchronous code, such as API calls. It gices us access to
dispatch and getState, enabling complex asynchronous flows.

Redux Toolkit
-------------
Redux Toolkit is the official, recommended way to write Redux [Link] simplilfies state
management in React Applications by reducing boilerplate, providing built-in best practices, and
improving performance.

Key features
------------
configureStore - Creates a redux store with good default like middleware (e.g., redux-thunk)
and Redux Devetools

createSlice - Combines reducers, actions, and initial state into a single function .

createAsyncThunk - simplilfies handling of asynchronous login (e.g., API calls)

immutability & performance - Used immer under the hood, so we can write multable-looking
code while keeping redux state immuatable.

Provider makes the redux store available to react components


store={store} - connects the redux store to react

eCommerce Project
-----------------
login / Logout / Registration / Crud / form validation / some other functionalities (Authourization)

Redux, [Link]

React Videos Select multiple and file and files : pending

You might also like