4. REACT-NOTES
4. REACT-NOTES
INTERNET
HTTP GET
RESPONSE
In MPA along with the old request new request will be sent to the server.
Server unable to segregate which one is the old request and which one is the new
request.
So in MPA reloading time will be more.
HTTP GET
REQUEST
CLIENT SERVER
RESPONSE
In SPA all the old request will be stored inside the browser cache and only a new
request will be sent to the server.
Browser cache is just a memory block.
Before sending the request to the server, browser will check in the browser cache and
compare the new request with the old request.
If the requests are present inside the browser cache, then browser will not send the
request to the server. Suppose if the requests are not present inside the browser cache
then the request will be send to the server
So in SPA reloading time will be very very less .
REACT JS NOTES BY SARVESH SIR
Disadvantage of SPA:
Search Engine Optimization: Whenever you search some content one browser ,
ranking will be more for Multi Page Application than Single Page Application based
on some of the keywords used in the application.
React JS :
It is JavaScript library to create interactive user interfaces.
Using react we can build Single Page Application.
History of ReactJS
In 2011 facebook announced in the news feed that they will introduced one library to
overcome the disadvantages of existing framework and library.
In 2013 , Jorden Walkie employee of facebook developed ReactJS library.
html html
head body
head body
ul
meta title ul
meta title
li li
li li
Diffing Algorithm
REAL DOM (OBJECT) PATCHING virtual DOM (OBJECT)
<ul> <ul>
key
<li key=”1”> Test </li> <li key=”1”> Test </li>
<li key=”2”> MUST </li> <li key=”2”> MUST </li>
<li key=”3”> Test </li> <li key=”3”> Test </li>
</ul> </ul>
Here first-time structure of RealDOM is copied to a VirtualDOM.
Whatever changes that we make first it will be updated in Virtual DOM, then Virtual
DOM compares with the real DOM. If there is any change then it will be updated or
patched in RealDOM using Diffing Algorithm.
Process of updating changes in RealDOM is known as patching.
This entire process is known as reconciliation process.
REACT JS NOTES BY SARVESH SIR
COMPONENTS:
React Component are reusable building block of code which
associated with logic.
Types of Component :
1) Class based component
2) Function based components
Note :
Name of the component should start from uppercase and .jsx extension.
Ex : App.jsx
We can represent component in 2 ways
i) < App/>
ii) <App><App/>
index.js
REACT JS NOTES BY SARVESH SIR
Note : In class based component there is one built in property called as state so
class based component called as statefull Component.
index.js
App.jsx
In this example code inside return (<h1> I am App Component</h1>) statement looks similar
to HTML, but it is actually JSX.
JSX RULES :
1) When you want to render more than one element wrap them with one
parent and ( )
REACT JS NOTES BY SARVESH SIR
Note : In the above example we have used <div> </div> as a parent .So in
this case <div></div> will create one new node. In order to avoid this we
have to use fragments as a parent.
<br />
<br> Or
<br></br>
App.jsx
4) CamelCase Conventions
HTML JSX
class className
for htmlFor
State :
State is used to store data at component level.
In class based component there is a property called as state so class
based component is called as Statefull component.
In function based component there is no built in property called as
state so it is called as StateLess Component.
We can make Function based component as statefull by using a
hook called as useState()
Hooks :
Hook is nothing but a function and present only in function based
component.
Hooks are introduced React 16.8 version onwards.
Why Hooks are used in ReactJS?
Hooks allows functional component to have access to state and
other React features which present in Class based components.
Basic hooks :
1) useState ( )
2) useEffect ( )
3) useContext ()
useState( ) :
This hook allows you to add state to FBC.
It return an array [undefined,f]
It accepts 2 values
a. current state b. Updator function.
Initialization of useState( )
Note : While using useState( ) first we need to import that from React
library.Example:
App.jsx
index.js
REACT JS NOTES BY SARVESH SIR
PROPS :
Props are shorthand for properties.
Props is an inbuilt object.
Props is a way to communicate between the component.
Props are used to send the data present in parent component into
child component.
Props are sent html like attribute format.
Example : Sending data present in App.jsx into Child.jsx. Here App.jsx acts as
a parent and Child.jsx acts as child.
Ex:1
App.jsx :
Child.jsx
Props Children :
App.jsx :
REACT JS NOTES BY SARVESH SIR
Child.jsx
Child.jsx
REACT JS NOTES BY SARVESH SIR
Child.jsx
App.jsx
Child.jsx
Child.jsx
Props Drilling:
Props drilling is a process of passing data from one component to another component
through multiple layer of component ,even though some of those intermediate
component don’t directly use the data.
App.jsx
Child.jsx
GrandChild.jsx
REACT JS NOTES BY SARVESH SIR
In this example, we are sending props from App.jsx to GrandChild.jsx through Child.jsx.
Where Child.jsx actually don’t wanted the data.
Steps :
1) In src folder create one folder as context
2) Inside this context folder create one component file with name
GlobalContextApi.js (here .js represent global)
3) Here if we want to send any props we have to use one special
Attribute called as value.
GlobalContextApi.js
REACT JS NOTES BY SARVESH SIR
4) Create one more component in src folder let us say Nav.jsx where I want
to receive the data. Which acts as a consumer.
Nav.jsx
App.jsx
index.js
REACT JS NOTES BY SARVESH SIR
useReducer :
Reducer.jsx
import React from "react";
import { useReducer } from "react";
const Reducer = () => {
let reducerFunc = (state, action) => {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset":
return { count: (state.count = 0) };
}
};
let initialState = { count: 0 };
return (
<div>
<h1>Counter = {state.count}</h1>
<button onClick={() => dispatch({ type: "increment" })}>increment</button>
<button onClick={() => dispatch({ type: "decrement" })}>increment</button>
<button onClick={() => dispatch({ type: "reset" })}>increment</button>
</div>
);
};
App.jsx
const App = () => {
return (
<div>
<Reducer/>
</div>
)
}
Nav.jsx
App.jsx
REACT JS NOTES BY SARVESH SIR
App.jsx:
global.css
index.js
REACT JS NOTES BY SARVESH SIR
2) Module.css:
Module CSS (also known as CSS Modules) is a way to scope CSS to a specific
component.
It provides local scoping of styles, ensuring that styles only apply to the component
they're imported into.
Steps :
In src folder create another folder let us say component
In component folder create one Component Footer.jsx
In component folder create one css file footer.module.css
Import footer.module.css file in Footer.jsx.
Footer.jsx:
Footer.module.css
REACT JS NOTES BY SARVESH SIR
Conditional Rendering::
Suppose if we want to display some content or don not want to display some content
on UI based on some condition, then we are going with this conditional Rendering.
index.js
global.css
REACT JS NOTES BY SARVESH SIR
Refs:
Refs are shorthand for reference.
Refs are used to create the reference of a particular element.
It is imperative way means we are directly communicating with DOM. So we should
not over use refs.
Inside ref there is one property called as current.
Steps :
1) first create a ref using useRef( ) hook.
2) In order to access the particular element, pass one special attribute called as ref
insideparticular element.
3) Inside the ref pass the created refs, ref={ }. So that we are able to access all the properties
of the targeted element.
App.jsx
REACT JS NOTES BY SARVESH SIR
Forms in React:
FORM
React State,
React Refs
Value attribute,
Name attribute,
onChange event
Controlled Forms
A controlled form in React is like a form where React controls all the input elements.
This means that the values of the form elements are stored in the component's state
and are updated through React.
When a user interacts with the form (like typing in an input field), React updates the
state, and the value of the input field reflects what's in the component's state.
import React, { useState } from 'react'
CSS
<input type="checkbox" name='skill' value='js'/>
JS
</div>
<div>
<button>Submit</button>
</div>
</form>
</>
);
}
Uncontrolled Forms
An uncontrolled form in React is like a form where React doesn't directly manage the
values of the input elements.
Instead, the values of the form elements are managed by the DOM (the web page
itself).
App.jsx
import React, { useRef } from 'react'
<div>
<button>Submit</button>
</div>
</form>
</>
)
}
Each and every phases of life cycle has its own methods.
2) Updation---
REACT JS NOTES BY SARVESH SIR
3) Unmounting(death)—
whenever we want to remove an instance of an component from the dom tree
then this unmounting phase will execute.
NOTE: In FBC components we can achieve these life cycle methods using a
hook called as useEffect
useEffect
useEffect are used to perform side effects operations in functional
components.
It acts as a alternate for comopnentDidMount( ),
componentDidUpdate( ), componentWillUnmount( )
useEffect accepts 2 arguments.
Syntax
App.jsx
import React from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import Nav from './Nav'
let [dish,setDish]=useState("dosa")
useEffect(() => {
console.log("render method");
})
//!empty dependency--->componentDidMount
useEffect(() => {
console.log("Component mounting");
}, [])
//!componentDidUpdate
useEffect(() => {
console.log("update");
},[dish])
Ex: unmounting
App.jsx
import React from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import Nav from './Nav'
let [dish,setDish]=useState("dosa")
useEffect(() => {
console.log("render method");
})
//!empty dependency--->componentDidMount
useEffect(() => {
console.log("Component mounting");
}, [])
//!componentDidUpdate
useEffect(() => {
console.log("update");
},[dish])
Nav.jsx
import React, { useEffect } from 'react'
useEffect(() => {
return () => {
console.log("umounting");
}
})
return (
<div>Unmounting Example</div>
)
}
JavaScript Concept
Promises:
It is an object.
It will always see the event you are performing whether it is completed or
not.
It will keep track on what we are doing
3 Stages:
1) Pending state :
This is the initial state, neither fulfilled nor rejected. This means that the
asynchronous operation hasn't completed yet.
2) Resolved state :
This means that the operation completed successfully and the Promise
now has a value. This value is often referred to as the fulfillment value.
3) Rejected state:
This means that an error occurred during the operation, and the Promise
is rejected with a reason (usually an Error object) explaining what went
wrong.
Note :
Whenever we have promise we need to resolve it.
We can resolve it by either using async and await or then and catch
How to create a promise ?
1) Create a Promise constructor
})
Final syntax:
let pobj = new Promise( ( resolve, reject) =>{
})
Map method
REACT JS NOTES BY SARVESH SIR
React Memo
Memo will memorize the entire component due to which if a state having
non-primitive data is not changing actually then component will not re-
render.
Memo used to skip the re-rendering of child components when the parent
components renders in FBC.
The component which you don’t want re-render simply wrap those
componets with React.memo
Memo is one Higher Order Component.
REACT JS NOTES BY SARVESH SIR
REACT JS NOTES BY SARVESH SIR
useMemo( ) :
useMemo it is a hook.
It will memorize a particular value in an outcome of a function or resultsof
a function. So that other functions will not be effected.
useMemo () accepts 2 values
1) A function that performs the expensive computation.
2) An array of dependencies. The memorized value will only be
recalculatedif any of the dependencies have changed.
import { useMemo, useState } from "react";
return (
<div>
<h1>multiply = {multiply}</h1>
<h1>Count1 = {count}</h1>
<button onClick={() => setCount(count + 1)}>incre</button>
<hr />
<h1>Count2 = {count2}</h1>
<button onClick={() => setCount2(count2 + 5)}>Incre</button>
</div>
);
};
In the above example heavy function is applicable only for state count1.
So we wrapped that function with useMemo( ) so it will memorized the
value of that particular function.
Here we have to pass the dependency to indicate that it should be
applicable for only count1 state variable
useCallback( )
useCallback( ) it is a hook.
It will memorized the entire function instead of the value returned by the
function.
REACT JS NOTES BY SARVESH SIR
Routing :
Routing in React allows you to build single-page applications (SPAs) by
handling navigation and rendering different components based on the
URL.
This helps create a seamless user experience without the need to refresh
the page.
Steps:
1) Install React Router:
React Router is a popular library for handling routing in React. You can install
it using npm:
npm install react-router-dom
2) Import the React Router Dom and SetUp the Routes:
REACT JS NOTES BY SARVESH SIR
App.jsx
BrowserRouter :
It is used to connect our application URL with the URL of
the browser address bar.
It should wrap your entire application to enable routing.
Routes :
Routes is a component provided by React Router that is
used to define the routes in your application.
REACT JS NOTES BY SARVESH SIR
Home.jsx
About.jsx
REACT JS NOTES BY SARVESH SIR
Contact.jsx
App.jsx
REACT JS NOTES BY SARVESH SIR
4) Inorder to display the error page for wrong URL create one
Component and render it.
ErrorPage.jsx
App.jsx
REACT JS NOTES BY SARVESH SIR
Header.jsx
Home.jsx
REACT JS NOTES BY SARVESH SIR
About.jsx
Contact.jsx
REACT JS NOTES BY SARVESH SIR
App.jsx
Link :
The Link component is a part of the React Router library. It is used
to create a hyperlink to navigate between different routes in a React
application. It renders an anchor <a> tag with an href attribute that
points to the specified route.
NavLink:
NavLink is a component provided by React Router that is used for
navigation in a React application. It's similar to Link, but it
provides additional styling and behavior options for the active link.
Specifically, NavLink allows you to apply a specific style to a link
when it matches the current route.
It provides a class attribute with active value like class=”attribute”
to activated component.
to :
The to prop is used with the Link component to specify the target
route. It indicates the URL path that the link should navigate to
when clicked.
6) Nested Routing and Shared Routing.
Nested Routing
Nested routing in React refers to the practice of defining routes within
other routes. This allows you to have a hierarchical structure of
components that correspond to different URL paths.
Shared Routing
Shared routing refers to a routing approach in React where multiple
components share the same route.
We need to mention <Outlet/> in parent component.
REACT JS NOTES BY SARVESH SIR
App.jsx
Home.jsx
REACT JS NOTES BY SARVESH SIR
About.jsx
Contact.jsx
But here there is one problem that is parent content will also display
with child components.
So in order to tackle this we have to use index props.
REACT JS NOTES BY SARVESH SIR
index props
Create new component let us say Layout.jsx
Whatever the content you want to write in Home component write the
content in Layout.
App.jsx
Layout.jsx
REACT JS NOTES BY SARVESH SIR
Home.jsx
About.jsx
Contact.jsx
REACT JS NOTES BY SARVESH SIR
AXIOS
Axios are JS library used to make HTTP request from browser.
Since it is a library we need to install it.
Command to install axios:
npm install axios
!axios
import React from 'react'
import { useEffect } from 'react';
import axios from 'axios'
import { useState } from 'react';
import "./global.css"
!then catch
useEffect(() => {
axios.get("https://api.github.com/users").then(x => {
setUser(x.data)
console.log(user);
})
},[])
return (
<div>
{
user.map(x => {
return (
<ul>
<li>{x.id}</li>
<li>{x.login}</li>
<li>
<img src={x.avatar_url} alt="" />
</li>
</ul>
)
})
}
</div>
)
}
useParams ():
React JS useParams Hook helps to access the parameters of the current route to manage the dynamic routes in the URL.
The react-router-dom package has useParams hooks that let you access and use the parameters of the current route as
required.
useNavigate ():
The useNavigate() hook is introduced in the React Router v6 to replace the useHistory() hook. In the earlier version, the
useHistory() hook accesses the React Router history object and navigates to the other routers using the push or replace
methods. It helps to go to the specific URL, forward or backward pages. In the updated version, the React Router’s new
navigation API provides a useNavigate() hook which is an imperative version to perform the navigation actions with
better compatibility
REACT JS NOTES BY SARVESH SIR
<div>
<RouterProvider router={routes}></RouterProvider>
</div>
);
};