React Digital Notes
React Digital Notes
- Tanmay Vaidya
LinkedIn: https://www.linkedin.com/in/tanmay-vaidya-b4b573195/
Github: https://github.com/Tanmay4669
React Notes
#Basics:
* Emmet:
It basically generates some code for us inside VS Code.
TanmayVaidya
Q . Create Hello World Program using React
Content
3 -
Delivery
Networks
(CDN) Links
* Crossorigin:
The crossorigin attribute in the script tag enables Cross-Origin
Resource Sharing (CORS) for loading external JavaScript files from a
different origin than the hosting web page. This allows the script to
access resources from the server hosting the script, such as making
HTTP requests or accessing data.
This (id='title'), classes, etc should come under {}. Whenever I'm
passing inside {}, will go as tag attributes of h1.
* Note:
React will overwrite everything inside "root" and replaces with
whatever given inside render.
* Bundlers:
In React, to get external functionalities, we use Bundlers. It
packages you app properly so it can be shipped to production.
Examples:
1. Webpack
2. vite
3. Parcel
In create-react-app, the bundler used is webpack
* Package Manager:
Bundlers are packages. If we want to use a package in our code,
we have to use a package manager.
We use a package manager known as npm or yarn
* npm:
npm doesn’t mean node package manager but everything else.
TanmayVaidya
* package-json:
It is a configuration for npm
* Caret sign(^):
If we use caret sign, then it will automatically update to the
minor versions and patch versions.
* Tilde sign(~):
If we use tilde sign, then it will automatically update only to
the patch versions.
* package-lock.json:
Will tell you which exact version of the library we are using.
* node_modules:
- Which gets installed is like a database for the npm.
- This is where super powers comes from.
- Our app has dependency on parcel
- parcel also has dependencies on something else.
- Every dependency in node_module will have its package.json
All these dependencies / superpowers are in node_modules
TanmayVaidya
(node_modules) (node_modules)
Our
Machine SERVER
X-
S
-
↳
Package-lock.json
package_lock.json
and all others are
Fetched from
moved to git
GIT git
Previously, we used CDN links to get react into our app. This is
not a good way.
We need to keep react in our node_modules
* Import:
- As we removed CDN links, we don’t have react in our app.
- So, we want to import into our app.
- For that we use the keyword import.
Common error:
- Normal js browser don’t know “import”. So, it shows error.
- As we got an error, we have to specify the browser that we ae not
using a normal script tag, but a module.
* .parcel-cache:
- Parcel caches code all the time.
- When we run the application, a build is created which takes
some time in ms.
- If we make any code changes and save the application, another
build will be triggered which might take even less time than the
previous build.
- This reduction of time is due to parcel cache.
- Parcel immediately loads the code from the cache every time
there is a subsequent build.
TanmayVaidya
- On the very first build parcel creates a folder .parcel-cache where
it stores the caches in binary codeformat.
- Parcel gives faster build, faster developer experience because of
caching.
* dist:
- It keeps the files minified for us.
- When bundler builds the app, the build goes into a folder called
dist.
- The `/dist` folder contains the minimized and optimised version of
the source code.
- Along with the minified code, the /dist folder also comprises of all
the compiled modules that may or may not be used with other systems.
- When we run command:
TanmayVaidya
- This will create a faster development version of our project
and serves it on the server.
- When I tell parcel to make a production build:
* Parcel uses:
1. It does image optimisation
2. Parcel also does ‘Caching while development’
3. Parcel also takes care of your older versions of browser
4. Sometimes we need to test our app on https, because something
only works on https.
Parcel gives us a functionality that we can just build our app on
https on dev machine.
* Transitive Dependencies:
- We have our package manager which takes care of our
transitive dependencies of our code.
- If we’ve to build a production ready app which uses all
optimisations (like minify, bundling, compression, etc), we
need to do all these.
- But we can’t do this alone, we need some dependencies on it.
Those dependencies are also dependent on other dependencies.
This alone
E-
can’t make
REACT PARCEL our app
performance
well
This
whole D1 D2 > Dependency 1
-
is our Dependency 2
app
D11
D12 D13
* Browserslist:
- It makes our code compatible for a lot of browsers.
- In package.json file do:
>
-
Means my parcel will make sure that my app works In last 2 versions of
all the browsers available.
- If you don’t care about other browsers, except chrome:
* Tree Shaking:
- Parcel has this superpower.
- means removing unwanted code.
Example:
- Suppose your app is importing a library which has a lot of
functions (say 20). Then, all those 20 functions will come into your
code. But in my app I may want to use only 1 or 2 out of it.
Here, Parcel will ignore all the unused code
* create-react-app:
- It uses web pack along with babel
TanmayVaidya
* Polyfill:
- to make older browsers understand our new code, the new code is
converted into a older code which browser can understand called
pollyfill.
- Babel do this conversion automatically.
Example:
a. ES6 is the newer version of JavaSript. If I’m working on 1999
browser, my browser will not understand what is this const, new
Promise, etc.
b. So, there is a replacement for code for these functionalities which
is compatible with older version of browsers
* Babel:
- It is a javascript package / library used to convert code written
in newer versions of JS (ECMAScript 2015, 2016, 2017 etc) into
code that can be run in older JS Engines.
* Scripts in package.json:
Run Command:
- To npx our app, command is:
Build Command:
- To build our app, command is:
Package.json:
* Note:
npx = npm run
For Babel-plugin-transform-remove-console
configuration
T
- Before installing the package, create a folder .babelrc
- And include :
* Render:
- means updating something in the DOM.
* Reconciliation:
- Helps to make React applications fast and efficient by minimising
the amount of work that needs to be done to update the changes.
- So, you don’t have to worry about changes on every update.
Example:
3- siblings
* render()
- Creates a tree of React elements.
- On the next state or props update, render() function will return a
different tree of React Elements.
- Whenever react is updating the DOM,
Example:
TanmayVaidya
- Now, I introduced one child over the top, then react will have to do
lot of efforts, react would have to re-render everything.
- That means, react would have to change the whole DOM tree.
* Introduction of Keys:
- React supports key attribute.
- When children have keys, React uses the key to match the
children in the original tree with children in subsequent tree.
- Thus, making tree-conversion efficient.
TanmayVaidya
* createElement:
- React.createElement() is creating an object.
- This object is converted into HTML code and puts it upon DOM.
- If you want to build a big HTML structure, then using
createElement() is not a good Solution.
- So there comes introduction of JSX
* Advantages of JSX:
- Developer Experience
- Syntactical Sugar
- Readibilty
- Less code
- Maintainability
- No Repitition
TanmayVaidya
* Components:
- Everything is a component in React.
* React Components:
X
Functional Components - NEW way
2 types
& Class Based Components - OLD way
* Functional Components:
- is nothing but a JavaScript function.
- is a normal JS function which returns some piece of react
elements (here, JSX)
Example:
- For any component, Name starts with capital letter. (It is not
mandatory but it’s a convention)
- To render functional component write <HeaderComponent />
React Element:
>
-
React Element is
an object
Functional Component:
>
-
Functional Component
is a function
Important points:
- Whenever you write jsx, you can write any piece of javascript
code between Paranthesis {}. It will work.
- JSX is very secure.
- JSX makes sure your app is safe.
- It does samitization.
>
-
Write anything inside {},
Jsx will sanitise the code
* Component Composition:
- If I have to use a component inside a component. Then it is called
component composition / composing components.
Header
Search Body
Footer
Note:
JSX expressions must have one parent element.
TanmayVaidya
* React Fragment:
- It is a component which is exported by ‘React’.
[ import React from “react” ]
- Groups list of children without adding extra nodes to the DOM.
Note:
In real world, data coming from api comes as “Array of Objects”
Example:
- Swiggy operates in various locations, including Kolkata and
Delhi, and displays website information tailored to each specific
location.
- This is achieved through a Config-Driven UI, where the backend
controls the front-end configuration, allowing for targeted content
delivery based on the user's location.
- This system ensures that users see relevant information, such
as restaurants, promotions, and details specific to their location,
resulting in a personalized and convenient experience.
Header
n
Carosuel 50% Free
off Delivery
Restaurant
List
- If my config is coming from backend, my data will come like:
* Optional Chaining:
- Allows us to access an object’s properties without having to check
if the object or its properties exist.
- represented by ? operator.
- Introduced in JavaScript ES 2020.
Example:
restaurantList[0].data?.name
TanmayVaidya
* Props:
- shorthand for properties
- When we say "pass props," we mean we're transferring data or
specific features into our React components. Just like passing
information to a friend, we're sending data to our components to
define their behavior and characteristics.
- resData = {restaurantList[0]}
This means react wraps up all these properties into a variable
known as ‘props’. We can call it anything.
* Object Destructuring:
- It unpacks specific properties from an object into individual
variables, streamlining data access and making code cleaner.
* Spread Operator (…):
- It unpacks iterables like arrays and objects, spreading their
elements wherever it's used.
Example:
- Combine arrays: [...a, ...b] joins a and b.
- Add elements: [...a, "new"] puts "new" at the start of a.
- Pass function arguments: func(...a) expands a as individual
args.
* Virtual DOM:
- The Virtual DOM is React's secret weapon! Imagine it as a
lightweight, in-memory snapshot of your webpage's UI.
- When changes happen, React updates this snapshot first, then
efficiently figures out the minimal edits needed to bring the real
DOM in sync.
- We need Virtual DOM for Reconciliation.
* Reconciliation:
- It takes the updated Virtual DOM and figures out the most
efficient way to bring the real DOM in line.
- It uses Diff Algorithm and it determines what needs to change
and what does not in UI.
- To find out difference between one tree (Actual DOM) and other
(Virtual DOM).
- Diff Algorithm then finds out what needs to be updated and it
change only that small portion.
* React Fiber:
- React Fiber is a complete rewrite of React's internal reconciliation
engine, built for speed and flexibility.
- It is responsible for Diff Algorithm.
- So, Reconciliation is the "what" of updating the DOM, while React
Fiber is the "how" it's done in a more efficient and flexible way.
* Export:
- There are 2 types of exports commonly used:
1. Named Export:
- Exports multiple values with custom names, imported with
specific names
(e.g., `export const add = (a, b) => a + b;
import { add } from "./math";`).
2. Default Export:
- Exports only one value, imported with name
(e.g., ` Hello=()=> { ... };
export default Hello;
import Hello from "./greetings";`).
TanmayVaidya
* Config File:
- A config.js file acts as the central hub for configuring different
aspects of your application or project.
- It stores and manages essential settings like API keys,
environment variables, theme preferences, and other configurations
needed for your code to run properly.
Example:
- Config file will look like this and it should also have named
export.
export const CDN_URL = ‘https://someurl’;
- Then import will look like:
import {CDN_URL} from “./config”
- This improves maintainability, flexibility, and collaboration,
especially when working with teams or sharing configurations
across environments.
I have a variable
- ‘searchText’ and if I
put that here
-Then the value “KFC”
will go inside my
input box
* React Variable:
- It is like a state variable
- Everytime, you have to create a local variable, you can use state
in it.
- In react, if I want to create a local variable like ‘searchText’, I will
create it using useState Hook.
* Hooks:
- Hooks are normal functions.
- React Hooks are like tools you can "hook into" React features
without needing a class component.
- Hooks bring the power of classes to function components,
making your React code simpler and more flexible.
TanmayVaidya
* useState Hook:
- Its used to create state variables.
-
I
-5
a. This function returns an array. -
b. The first element of this array is variable name
c. Second Element is a set function to update the variable
-
From this event property
I can read what I’m
typing
- So our Body Component will now updated as:
Current Tree
>
- New Tree
&
Note:
- Whenever state variable updates, react triggers a reconciliation
cycle (re-renders the component).
TanmayVaidya
#Microservices:
* Monolith:
- In older days, there used to be a single big application.
- So everything like Apis, SMS, Notifications, UI, JSP pages etc
used to be in the same project.
- Suppose if we have to change one button, we used to deploy this
whole project / application. It was such a mess.
- This architecture was known a Monolith.
* Separation of Concern:
- But now, instead of having a one big project, we have small different
projects.
- Here, separation of concern or single responsibility principle is there.
- The tools and languages used in a projects depends on the usecase .
- All these projects are deployed in different ports but same domain
name.
Authentication
Logs Project
(Python) (Go)
Q . How to make an API Call?
- JavaScript gives us fetch() function.
Case 1:
300ms + 200ms = 500ms
Case 2:
100ms + 300ms = 400ms
Render
User loads Make an Update
the
the page API Call the UI
initial UI
- In way 1, page will be available to us in (300 + 200 = 500)
ms (milli seconds).
- In way 2, Page will be available to us in 100ms which is lesser
than the first approach.
- So, Way 2 is a good way of calling API because of the user
Experience.
- What we want is on initial page load we want our API to be called
just once.
- To make this functionality happen React gives us access to the
second most important hook known as useEffect hook.
* useEffect Hook:
- useEffect is a hook given by react which runs after a component
renders and re-renders in DOM provided the hook must be placed
inside that component.
- useEffect hook expects two parameters. First parameter is a callback
function and second one is a dependency array.
UseEffect(()=>{ }, [stateVariable])
UseEffect(()=>{ }, [])
UseEffect(()=>{ })
- In this code, API will be called once after the component renders
for the first time because in useEffect hook, dependency array is
empty.
- The old data would be rendered for a first few seconds and then
new data comes.
- If we removed that old data, page shows an ugly UI. So initial
screen to get rendered should be a basic loader / shimmer Ui. This is
a basic skeleton.
* Shimmer UI:
- There was a research done and earlier people used to saw ‘spinning’
loaders at first, and then suddenly every restaurants come up.
- This is a bad user experience. -
- Human brain don't like to view so many fluctuations in the UI,
according to psychology.
- Psychologist figured out that, instead of Spinners, empty
boxes should be shown.
- It is a better UI experience for the users. ~
- As suddenly changes are not happening, our eyes won't hurt.
- This is known as SHIMMER UI
* Conditional Rendering:
- Same as conditions (if operator or the condition operator) work
in the JavaScript.
- Rendering components based on a given condition check is
known as Conditional Rendering.
- In React, you can conditionally render JSX using Javascript
syntax like:
- if statement
- & & operator
- ? : operator
TanmayVaidya
Example:
- In below example we are showing shimmer to the UI when
restaurant list data is not available.
- When the component is rendering, listofRestaurants state
variable is initialised with empty array [] and as per
conditional rendering logic we are showing shimmer in the UI.
- When listofRestaurants state is changed Body component re-
renders and as per conditional rendering logic, the
listofRestaurants state variable will have data this time which
displays list of restaurants in the UI.
Pseudo Code:
- if (restaurant) is empty => Load Shimmer UI
- if (restaurant) has data => Load Actual UI
i. Optional Chaining:
Early Return
TanmayVaidya
#Important Notes about React:
v. We can use more than one useEffect, according to the use case.
vi. To store images locally, create a folder assets and images can be
kept inside it.
TanmayVaidya
#Routing:
- There are two types of Routing:
- Server Side Routing
- Client Side Routing
TanmayVaidya
* Client Side Routing:
- Client-side routing involves JavaScript which handles the routing
process internally.
- In client-side routing, a request to the server is prevented when a
user clicks a link, hence no page refresh even when the URL changes.
- Because all of the available data and components are already
present in the local machine.
* Note:
- When you are building an app, be conscious about what packages
are you using.
- You should use big packages when you have complex things to do.
Example:
- If you have to build a lot of big and lengthy forms in your
app, in which each and every input box have their own Reg. Exp.
check, pattern check, validation etc.
- So, instead of building all components on your own, we can
use a npm package (or library) known as Formik.
- You can use React-Hook-Form also instead of Formik.
* Formik:
- Formik simplifies building forms in React.
- Forget managing state, validation, and submission manually.
- With Formik, you just define your form inputs and it handles the
rest: keeping track of values, showing errors, and submitting data
smoothly.
- Think of it as your friendly form-building assistant!
TanmayVaidya
* Routing in React:
- Finding the path of different pages of our app.
- For that we use a library or npm package called React Router.
- Install this package
npm i react-router-dom
- * createBrowserRoute:
- This is a function that we get from react-router-dom.
- createBrowserRouter function takes an array of router
configuration objects of which each object has their own
configuration set.
- We provide path and element to each configuration
object so that when we navigate to the path, component or
element associated with that path will be rendered in
UI.
- createBrowserRouter creates a router for us.
- There are multiple Routers in react. (Can read about them
in docs).
- createBrowserRoute is the most recommended route for all
the React Router web projects.
- To create routing, do:
-
Rendering RouterProvider
- Now if we navigate to the base URL http://localhost:1234/ we
get AppLayout component page
TanmayVaidya
Q . What happens when user navigates to a URL that does not exist?
- react-router-dom is a powerful Library that also handles the
error in case we navigate to a route that does not even exist.
- We get a default 404 error page.
Q . How do we show more information about the error in case user redirects
to an Invalid URL?
- react-router-dom provides a hook useRouteError which returns an
error object which states what types of error did we encounter.
- It is a hook which won’t allow this red colour error to come in
consoles.
- It catches all the routing errors and we can show those error to the
user.
- On the console:
Q . What are problems with Anchor Tag?
- Anchor tag leads to Server-Side routing, because in anchor tag
we have an attribute href where we provide the URL and when we
click on the link, a call is made to the URL hosted in a server and
our page reloads until we get the data from the server.
- This is not a good user experience
- To overcome this we use Links.
* Links:
- To achieve client-side routing, we use Links in React.
- We should enclose navigation elements inside a Link tag given
by react-router-dom.
- In Link tab we define an attribute named to where we set a path for
the link and to decides where to navigate when the link is clicked.
- Now if we click on About, it will lead me to about component page.
* Nested Routing:
- Nested routing enables us placing multiple children components
within the parent component and performs routing on child
components without reloading the entire page.
- Right now, if we notice about page component, we can’t see the
header and footer component loaded. But we want them to be loaded
for about component and for other page components.
- In below screen shot, if my path is "/" , I want my "Body"
component to be inside header and footer component.
- If my path is "/about", I want my "About" component to be inside
header and footer component and so on.
> Outlet
-
> Children
-
TanmayVaidya
* Outlet:
- Outlet is a component that react-router-dom provides to plug in
children components into layout component during page navigation.
- Outlet is a place holder for children components configured in
route configuration objects.
- When we navigate from page to page react triggers reconciliation
which updates only the updated portion in the dom which is the outlet.
* Dynamic Routing:
- Dynamic routing is the time at which routing take place.
- In Dynamic routing, routes are initialised dynamically.
- It is a process of rendering components in response to a change in
application’s URL.
- In our case, restaurant card is clicked and route for that card is
generated.
- Behind the scene, when we click on a restaurant card from
restaurant list, Id of that restaurant will be attached to the URL and
this will be read by restaurant Menu component.
- Restaurant Menu component uses this ID for making API calls
and displaying the required data in UI.
* useParams:
- useParam is one of the hooks given by react-router-dom library.
- We can use this hook to retrieve route parameters from a route
URL as use it in the component we navigated to.
- useParam enables us to read data from the route URL.
Code Implementation for Dynamic Routing and useParams:
Body.js:
RestaurantMenu.js:
RestaurantMenu.js:
TanmayVaidya
#Custom Hooks:
- Modularity:
- Each react component should have a single responsibility which
is to render the data in UI.
- We should separate functional logics away from the component
and offloads this responsibility to a custom hook or a helper
function and use them whenever required.
- This is called modularity meaning breaking down the code
into smaller pieces, each having their own responsibility.
- Testability:
- We break down larger piece of code into smaller chunks that we
store in utilities files which enables us to write more test cases.
TanmayVaidya
Example:
- We have written API call logic inside Restaurant Menu component.
- As per SRP, Restaurant Menu component should only render data
in UI.
- Restaurant Menu component should not worry about how the data is
fetched from the API.
- We will try to extract this logic.
- We will create a custom hook that will help us to get the restaurant
details.
Standard Practice:
RestaurantMenu.js
TanmayVaidya
* Building Online and Offline feature:
- If the user has no internet connection then it should show You
are Offline check your internet connection else it should show the
actual data.
useOnlineStatus.js
Body.js
Explanation:
- In JavaScript, window object provides a method called
addEventListener where we attach events.
- In our case we are attaching online and offline events to
addEventListener method, also we are providing a callback
function as a second argument to addEventListener which gets
called when user gets online or offline.
- We want this event to be called just once for both online and
offline. That’s why we have put them inside useEffect hook.
Important:
- When we navigate from component to component, online and
offline event listeners should have been removed but they still exist.
- So whenever, eventlistner is added, we should clean it up.
- Because, whenever you are going offline and getting back
online, eventlistener is created only once because we have empty
dependency array.
- It is always a good practice to remove event listeners on
components navigation otherwise browser will keep hold to these
events which is a big performance hit.
TanmayVaidya
Offline: offline mode
* Optimization:
- In our application parcel created only one JavaScript file where all of
our code is bundled and minified together.
- The size of the index file bundle is less in production build..
* Chunking:
- It is also called as:
- Code Splitting
- Lazy Loading
- Dynamic Bundling
- On Demand Loading
- Dynamic import
TanmayVaidya
Example:
- Create a Grocery Component.
- Now in App.js instead of importing in the regular way, do this:
- So, now index.js file in dist folder won’t have the code of Grocery.
- It is created as a separate file while loading.
- This is called On-Demand Loading.
- So, when Grocery is loaded for the first time, we see an error
message on screen.
- This is because, Grocery file took 27ms to get loaded. But react
tries to render it before it gets loaded. Hence the error.
- Solution for this is Suspense.
* Suspense:
- It suspends the lazy loaded components until bundler for
the component is available in UI
* Fallback:
- When bundle is not loaded react suspends the component for a
while until the bundle is available.
- During this time for a better user experience we should display a
shimmer UI on screen.
- So, suspense component accepts a prop called fallback where we
call shimmer UI component.
- We can also write JSX in fallback attribute within {}.
Why:
- Because if we do, for ever state or prop change, parent component
will be rendered.
- As a result, lazy loading of the child component takes place on
every render. So, every time the bundle will be loaded.
TanmayVaidya
TanmayVaidya
#Playing with Data:
Example:
- In Swiggy Bangalore, out of many restaurants, there are few
promoted restaurants present.
- The only difference between normal and promoted restaurant is
that it has promoted label on the UI Card.
Input
- Component
0 - output
Component
RestaurantCard.js
Body.js
Creating Accordions:
- Now, lets display all the categories along with their items into
accordions.
- Create a RestaurantCategory.js file for displaying the catergories
- From RestaurantMenu.js, we will pass the categories data to
the newly created component.
RestaurantMenu.js
- In RestaurantCategory.js we would write logic for displaying
the categories heading, i.e. accordions heading
RestaurantCategory.js
* Uncontrolled Components:
- Uncontrolled components in React allow child components
to manage their own state internally through the DOM, without
direct control or state management by the parent component.
- For eg, here each panel has its own state as isActive and it also
not controlled by their parent Accordion.
* Controlled Component:
- Controlled components in React are those where the parent
component manages the state of form elements.
- The parent passes down the current values as props to child
components, which in turn notify the parent of any changes via
event handlers.
RestaurantMenu.js
RestaurantMenu.js RestaurantCategory.js
RestaurantCategory.js
RestaurantMenu.js
TanmayVaidya
* Props Drilling:
- Props drilling refers to the process of passing props down through
multiple levels of nested components in a React application.
- It occurs when data needs to be transferred from a parent
component to a deeply nested child component.
- While it's a common practice in React, it can lead to code that's
harder to maintain as the application grows in complexity.
- This is because props may end up being passed through
intermediate components that don't actually use them, adding
unnecessary complexity.
- Alternative solutions like context API (React Context) or state
management libraries (like Redux) can help mitigate this issue by
providing a centralized way to manage and access state across
components, reducing the need for props drilling and making the
codebase more scalable and maintainable.
* React Context:
- React Context is commonly used when you have data that needs
to be accessed by many components at different levels of nesting,
such as themes, user authentication, localization, or global state
management.
- It helps to avoid prop drilling and makes your code cleaner and
more maintainable by providing a way to share data across
components without having to explicitly pass props down through
every level of the component tree.
TanmayVaidya
Example:
- We would create a data that should be accessible anywhere from
the app I.e. loggedInUser.
- So now we would create a context named as UserContext inside
utils in UserContext.js file.
- React provides a utility function called createContext. It takes in
the default value of our context and helps to make our data available
throughout our app
UserContext.js
TanmayVaidya
Header.js
Header.js
Header.js
* Using useContext in Class Based Components:
- We know that in CBC, we do not have any concept of hook.
- So, in CBC we first import the context that was created (here
UserContext) and use it as a component.
- This component can accept a JSX piece of code, within which we can
write a call function where the function parameter is actually the
context data.
About.js
About.js
- Till now we are always using the dummy user data . But in an
actual app, we first need to authenticate the user and then override the
dummy data with the logged in user details.
- Remember that we have already hardcorded a loggedInUser data
inside the App component (because we will making an API call to
authenticate the user from that component’s useEffect()hook).
App.js
- Now, here we have mentioned all the components i.e. Header, and
Outlet inside the Provider tag. This helps to update the context data for
all the components.
- If any of the component be used outside the provider, that
component would have been served the default value of the context.
App.js
TanmayVaidya
- Suppose we will have an input box beside the Top Rated button with
a value as the user name. Now, when we change that value, the user
details should also be changed. (This is a useless functionality, but
good for conceptualisation).
- We know that the user detail (not the dummy one) is a state
variable and we can only change a state variable with a set function.
- Also, we have to make this set function accessible throughout our
app. So to do this, we need to pass this set function in our value props
too (of the UserContext.Provider component of the App component).
- Then in the Body component, we will make an input box with the
value as the context data’s username and we will also attach a
onChange function to change the user details as per the input box’s
value.
App.js
- Also in Body Component, we would extract the loggedInUser and
setUserName.
Body.js
TanmayVaidya
TanmayVaidya
#Redux:
* Redux:
- Redux is a State management tool for UI applications most
commonly used in library such as React JS and frameworks such as
angular and view etc.
- It allows us to store all our application’s data in one place known as
store.
- This makes it easier to build complex real world applications and
keep the state organized.
* Advantages of Redux:
- Provides Centralised state management system.
- Prevents Props Drilling.
- Preferable over context API / React Context in large scale application.
- Provides Performance Optimisations.
* Disadvantages of Redux:
- A huge learning curve for new comers.
- Not suitable for small applications.
- Configuring Redux store is too much complex.
- Redux requires lots of boiler plate code making the code messy and
unreadable.
- Debugging is difficult.
* Redux ToolKit (RTK):
- RTK is a library that makes it easier to work with Redux in a
React application.
- It enables us to write redux code in a concise way.
- RTK abstracts the basic redux code preventing unnecessary boiler
plate code which enables developer like us to write clean concise redux
code.
* Redux Store:
- Redux store is a big JS object.
- Redux store is basically a central place to store data needed by any
components in react app.
- We can have multiple react context to store multiple data. But we
have a single redux store for global data management.
Q . But is it a good practice to keep all the data inside the whole big object ?
- Yes it is absolutely fine.
- But so that our redux store become very big and clumsy, we have
something known as Slicing in our redux store.
* Slices:
- Slices are logical separations or portions within the Redux Store.
- Each slice maintains a mapping between actions and reducer
functions so that when the action is dispatched reducer of that
action gets called.
- In short slices not only stores data portion wise but also it
manages/updates these data.
TanmayVaidya
Q . What slices we can have in our app?
- We can have
- User Slice
- Authentication Slice
- Theme Slice
- Cart Slice
TanmayVaidya
Redux Store
Dispatch
8
Logo = 2
(action) reducer
-7
> Add Item
j
Fn () Cart
+
Update the
Cart User
+ read
Slice..
+ 7 Selector
(Subscribing
to the store)
TanmayVaidya
Click
Cart -
Updates
Selector -
Read it
- Selector means we are selecting the slice out of the store or we are
selecting the portion of the store.
- This selector is a hook known as useSelector().
1. npm i @reduxjs/toolkit
2. npm i react-redux
appStore.js
TanmayVaidya
App.js
* Creating Slices inside Redux Store:
- RTK provides an API createSlice which creates Slices for us.
Mutating the
>
- state (Directly
modifying the
state)
name:
- It represents name of the slice which is cart.
initialState:
- It represents an object where we set initial state of the slice.
- In our case we have set items to an empty array because
initially our cart will have zero items in it.
reducers:
- It represent an object where we map actions with reducer functions
- For eg. addItem is a reducer fn()which takes 2 parameters state
and action, and it modifies the state based on the action.
TanmayVaidya
cartSlice.reducer:
- It represents an object which wraps up all the reducer functions
and export them as in one big reducer object.
cartSlice.actions:
- In line number 21 we are de-structuring all the actions from
cartSlice.actions and exporting them at once.
-
It will give access to whole store
It will give access to
cart store that we
need.
TanmayVaidya
TanmayVaidya
* Dispatching an Action:
- React-redux library provides a hook called useDispatch that
returns a function and the function takes an action with an
action payload.
- This function is responsible for dispatching the action.
>
Whatever is passed here will go inside
-
reducer fn(), that too inside a
payload [action.payload]
- Let’s Create a Cart Component and display the added items into
the cart.
TanmayVaidya
- Now as we have created a dispatch action for clearCart, we will see
how it works. So now on clicking on Clear Cart we will see:
* Important Points:
- Whenever you use selector, make sure you subscribe to the right
portion of the store
Example:
- Max Efficiency:
- Less Efficiency:
TanmayVaidya
#More Hooks:
* useMemo():
- It is a hook in React that helps you optimize performance by
memoizing the result of expensive computations.
- It is a React Hook that lets you cache the result of a calculation
between re-renders.
Syntax:
calculatedValue:
- It is the function whose result is memoized.
dependencies:
- They are the values that, when changed, trigger
recalculation of calculateValue
TanmayVaidya
Example:
- Without useMemo:
- The provided code allows users to calculate prime numbers by
entering a value into the input field. Additionally, it provides
functionality to toggle between light and dark modes with a
button click.
- So as toggling and prime no are not related. So it was expected that
change on one will not affect the other.
- But the output is different.
After Clicking
on toggle button
for multiple
times
- As you can see above that even our prime calculation is not
dependent on the toggle button, it is still re-rendering which is a
major performance issue for heavy computation.
- The reason behind this is the reconciliation process, as whenever the
state changes, it will re-render the whole component. Here due to toggle
state, it re-renders the component .
- With useMemo:
- Without clicking on toggle, just entering into input:
After Clicking on
toggle button for
multiple times
- Now, even after state change of toggle and re-rendering of
component, prime is not calculated.
- It would be calculated only we we change prime input, so we wrote
[text] in the dependencies.
- Here we are memoizing / caching the heavy operations which help
in preformance gain.
* useCallback():
- It is a hook in React that helps optimize performance by
memoizing a callback function.
- It is a React Hook that lets you cache a function definition
between re-renders
Syntax:
fn:
- It is the function to be memoized.
dependencies:
- They are the values that, when changed, trigger the recreation
of the memoized function.
TanmayVaidya
Q . Comparison between useMemo and useCallback
- useMemo:
- Primarily used for memoizing expensive computations and
returning a cached value.
- Used when you want to memoize the result of a computation
and use it elsewhere in your component.
- useCallback:
- Primarily used for memoizing functions to avoid unnecessary
re-creations.
- Used when you want to memoize a function to prevent
unnecessary re-renders in child components that depend on that
function.
TanmayVaidya
TanmayVaidya
* API Polling:
- API polling, also known as polling, is a technique used in
software development to retrieve updated data from a server at regular
intervals.
- It involves sending periodic requests to an API endpoint to check
for new or updated information.
* WebSocket:
- WebSocket is a communication protocol that provides full-duplex
communication channels over a single, long-lived connection
between a client and a server.
- Unlike traditional HTTP requests, which are unidirectional and
stateless, WebSocket allows for bidirectional communication,
enabling real-time data transfer between client and server.
Working of WebSocket:
- WebSocket connection initiation involves an HTTP
handshake, indicating the client's intention to upgrade to the
WebSocket protocol.
- Upon successful handshake, the application-layer protocol is
upgraded from HTTP to WebSockets, utilizing the existing TCP
connection.
- HTTP is then excluded from further communication, and both
client and server can exchange data using the WebSocket
protocol.
- This establishes a persistent, full-duplex channel, enabling
bidirectional communication without reliance on HTTP.
TanmayVaidya
Usage:
- WebSocket is particularly useful for real-time applications
where low latency, bidirectional communication, and efficient
data transfer are essential.
- Chat applications, Online gaming, Stock trading platforms,
etc are the examples where WebSocket is used.
* Browser Tab Isolation:
- Each tab in a web browser operates within its own isolated
environment, including its own memory allocation.
- This isolation ensures that the activities and resources utilized
within one tab do not directly affect the performance or stability of
other tabs.
- Overall, the browser's ability to provide memory and resource
isolation for each tab contributes to a more secure, stable, and
efficient browsing experience, ensuring that activities in one tab do
not negatively impact the performance or stability of other tabs.
TanmayVaidya