React
React
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]
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.
Classes
-------
[Link] and [Link]
facebook : users
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.
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>;
}
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:
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)
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).
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.
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)
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<p>This is paragraph</p>
</body>
</html>
<!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>
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
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.
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 : 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
[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
node package manager (npm) is mainly used for installing modules or packages and managing
project dependencies
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]
[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>
JSX
Components
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.
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
----------
Rendering a List
----------------
map()
Rendering Multiple Components
-----------------------------
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
Props
-----
Components can be passed as props, which stands for properties.
Props are like function arguments, and we send them into component as attributes.
Components in Components
------------------------
We can refer to components inside other components
Components in Files
-------------------
Props (properties)
------------------
Props are arguments passed into react components.
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
//[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;
React Router
------------
create-react-app doesn't include page routing
Folder structure
----------------
src/pages/
----------
[Link]
[Link]
[Link]
[Link]
[Link]
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 <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)
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.
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.
import useState
---------------
import {useState} from "react"
var x=10
let x=10
const x=10
const [color,setColor]=useState("red");
The useState Hooks can be used to keep track of strings, numbers, booleans, arrays, objects
and any combination if these!
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 trimmedInput=[Link]();
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>
);
}
[Link]
--------
import React from 'react';
import ReactDOM from 'react-dom/client';
import './[Link]';
import App from './App';
import reportWebVitals from './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.
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]
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
[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
await [Link]();
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]);
Cleanup function
----------------
mount : add the component
unmount : remove the component
The Cleanup function ensures that the event listener is removed when the component
unmounts, preventing memory leaks.
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.
Running the effect unnecessarily on every render waster resources and can slow down the app.
[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
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>
</>
)
}
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
1. Simple Counter
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
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
CRUD
----
Create - Form
Read - Read
Update
Delete
[Link]
[Link]
postman
!
-----------------------------------
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. 
-------------------------------------
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. !
-------------------------------------
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.
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>
);
}
useCallback
------------
The react useCallback hook returns a memorized callback function
The useCallback hook only runs when one of its dependencies update.
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 / 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.
[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.
File Structure
--------------
src
components
[Link]
redux
[Link]
[Link]
[Link]
[Link]
[Link]
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 .
immutability & performance - Used immer under the hood, so we can write multable-looking
code while keeping redux state immuatable.
eCommerce Project
-----------------
login / Logout / Registration / Crud / form validation / some other functionalities (Authourization)
Redux, [Link]