Namaste React Notes by Akshay Saini
Namaste React Notes by Akshay Saini
Namaste React
Episode 01 - Inception
What is a CDN ?
React.development.js
React-dom.development.js
●If there is already an HTML element in the <div> tag, then that
HTML element will be loaded in the DOM and shown on the page.
●But as soon as JavaScript reaches the <script> tag which imports
the React code, it will replace that HTML element with the React
code.
What is Emmet ?
●Emmet is a free add-on for your text editor that allows you to
type shortcuts that are then expanded into a full piece of code.
1. Library
a. Alibrary provides a set of helper
functions/objects/modules which your application code calls
for specific functionality.
7
1. Real DOM
a. Real DOM is the actual structure of the webpage.
b. React updates complete document in the Real DOM.
c. Real DOM is the actual web page rendered on the browser.
Any changes made reflect directly on the complete webpage.
2. Virtual DOM
a. Virtual DOM is the virtual representation of the Real DOM.
b. React updates the state changes in virtual DOM first and
then it syncs with the Real DOM.
c. Virtual DOM is just like a blueprint of a machine, we can
make changes in the blueprint but those will not directly
apply to the machine.
d. Virtual DOM is a programming concept where a virtual
representation of UI is kept in memory synced with Real
DOM by a library such as React-dom and this process is
called reconciliation .
9
When does React sync the changes of Virtual DOM with Real DOM
?
●React synchronizes the changes from the virtual DOM to the Real
DOM during a process called reconciliation. This process involves
several steps:
○State and prop changes
○ Re-rendering
○Diffing - React compares the new virtual DOM tree with the
previous one to identify what has changed.
○Batch updates - React doesn’t immediately update the Real
DOM with each change. Instead, it batches updates to
optimize performance. The batching happens within the
lifecycle of an event or after a certain period of time. (e.g.,
after user action like clicking a button or typing in an input
field).
○Commit phase.
○Asynchronous updates.
●Async
○Execution order -Scripts with async attributes are
executed as soon as they are downloaded regardless of the
order in which they appear on the document.
○Loading behavior -The browser will download the script in
the background while continuing to parse the HTML
document. Once the script is downloaded, it will immediately
execute, potentially interrupting the parsing of the
document.
○Use case -Best for scripts that are independent and do not
rely on the DOM being fully parsed or other scripts being
loaded.
●Defer
○Execution order -Scripts with defer attribute are
executed in the order they appear in the document, but only
after the entire HTML document has been parsed.
○Loading behavior -The browser will download the scripts in
the background while parsing the HTML document, but will
defer execution of the script until after the HTML parsing
is complete.
○Use case -Ideal for scripts that need to interact with fully
parsed DOM or that depend on other scripts.
11
What is NPM ?
●It is the manifest file of any node.js project and contains the
metadata of the project.
●This metadata information can be categorized into below
categories:
○Identifying metadata properties: It basically consists of
the properties to identify module/project such as the name
of the project, current version of the module, license,
author of the project, description about the project, etc.
○Functional metadata properties: It consists of the
functional values/properties of the project/module such as
entry/starting point of the module, dependencies in project
scripts being used, repository link, etc.
What is a bundler ?
●AJavaScript bundler is a tool that puts your code and all its
dependencies together in one JavaScript file.
●It is a development tool that combines many JavaScript code
files into a single one that is production-ready loadable in the
browser.
●Following are the top 5 bundlers in JavaScript:
○Browserify
○ESbuild
○ Parcel
○ Rollup
○Webpack
1. Dev dependencies
2. Normal dependencies
Transitive Dependencies
Explain NPM
●Primary purpose
○It is a package manager.
○It is used to install, share, and manage dependencies in
node.js projects.
●Main functions
○ Installing packages
■ You can install packages globally or locally in your
project.
■For example, npm install loadash installs the loadash
package locally, and npm install -g loadash installs it
globally.
○Managing dependencies - It maintains a package.json file
that lists all the dependencies of the project.
○ Running scripts
16
Explain NPX
●Primary purpose
○NPX is a package runner tool that comes with npm (since
npm version 5.2.0).
○It allows you to execute libraries from npm packages
without needing to install them globally.
●Main functions
○ Running local binaries
■ If you have a package installed locally in your project,
you can use npx to run its binaries without needing to
specify the path.
■For example, ‘npx eslint .’ runs the local eslint library.
○Running remote binaries
■Npx can download and execute packages directly from
the npm registry without installing them.
■For example, npx create-react-app my-app runs the
create-react-app directly.
○Avoiding global installs
■Npx is useful for running one-off commands without
polluting your global package namespace.
17
● Installations vs Execution
● Global installs
●Temporary use
● Ease of use
Why should CDN links not be used to bring React and React-dom in
the project ?
●If we use CDN links, then we will have to make a network call to
bring React into our project.
●Currently we use React version 18 which is mentioned in the CDN
link as well. So if in future, React version 19 comes, then we will
have to change the CDN links again.
●We can install React using npm install react which will store React
into node modules and will not cause any dependency issues.
●To get React from a CDN link, you will need to have a network
(internet) connection.
●When we install React into the application and remove the CDN
links, then we will get an error which says Uncaught
ReferenceError: React is not defined .
●This happens because we have installed React, but not imported it
into our JavaScript file.
18
How does parcel know that there are changes in the file/code ?
●When we start the server using parcel for the first time, it
creates a folder in the project named .parcel-cache .
●So the parcel uses caching. And after every subsequent build, it
will update the cache.
1. Compressing files
2. Bundling
3. Image optimization
4. Minification
5. Consistent Hashing
6. Differential Bundling
7. Diagnostics
JSX
Babel
Component composition
Config driven UI
Reconciliation in React
●Keys help React identify which items have changed, are added or
are removed.
●Keys should be given to the elements inside the array to give the
elements a stable identity.
● This can negatively impact the performance and may cause issues
with component state.
● If you choose not to assign any explicit key to list items, then
React will default to using indexes as keys.
29
Can we have both named and default exports in the same file ?
React Hooks
Diff Algorithm
Microservices Architecture
Note - Showing the spinner until the data is fetched on the screen is
not a good practice.
34
Shimmer UI
●When the page loads and the data is being fetched, until the data
is displayed on the UI, instead of showing a spinner, we can show
the skeleton of the UI.
●For example, tasks like updating the DOM, fetching data from
API endpoints, setting up subscriptions or timers, etc can lead to
unwanted side effects.
●How does it work ?
○You call useEffect with a callback function that contains the
side effect logic.
○ By default, this function runs after every render of the
component.
○ You can optionally provide a dependency array as the second
argument.
○The effect will only run again if any of the values in the
dependency array changes.
●Async function
○The Async function allows us to write promise-based code as
if it were synchronous.
○ This ensures that the execution thread is not blocked.
○Async functions always return a promise.
○If a value is returned that is not a promise, JavaScript
automatically wraps it in a resolved promise.
○Example:
● Await keyword
○Await keyword is used to wait for a promise to resolve.
○It can only be used within an async block.
○Execution pause: Await makes the code wait until the
promise returns a result, allowing for cleaner and more
manageable synchronous code.
○Example:
37
Routing in React
● Example:
Dynamic routing
●We can extract this resId using a hook i.e., useParams from
react-router-dom.
●Example: const { resId } = useParams();
●It will display the result of calling the useState() function in our
browser’s developer console.
●const [count, setCount] = useState(0); -> [0, function] <- output
42
What are various ways to add images into our app ? Explain with
code examples.
●If we have two state variables, and we try to update only one,
then React will update only that state variable and it will not
touch the other one.
Constructor (Parent) -> render (Parent) -> Constructor (Child) -> render
(Child) -> componentDidMount (Child) -> componentDidMount(Parent)
CreateHashRouter
CreateMemoryRouter
We can have this component only to display the data on the web page
and can create a custom hook which fetches the data.
Our Custom Hook
56
Home Component
The above hook checks if the user is online or offline using the window
object and the callback function sets the value of isOnline and the hook
then returns the value.
This value can be extracted into another component by importing the
useOnlineStatus() hook in it.
58
1. Chunking
2. Code Splitting
3. Dynamic Bundling
4. Lazy Loading
5. On demand loading
This bundle will not be loaded initially. It will be loaded only when the
user visits the cart page.
That means, with this approach the app will have 2 bundles. One would
be a normal bundle which contains all the code of the app except for
the cart component. This bundle will be loaded when the user visits our
app.
The other bundle will contain the code of the cart component which will
be loaded only when the user visits the shopping cart.
That is why this process is also known as on demand loading .
Example
Suspense
1. Inline CSS
Conditional Styling
66
1. Install tailwindcss and its peer dependencies via npm and create
your tailwind.config.js file.
5. Run your build process with npm run dev or whatever command is
configured in your package.json file.
6. Make sure your compiled css is included in the head .
68
1. Content: This key specifies the paths to all of your template files
in your project. Tailwind CSS will scan these files for class names
and generate only the necessary styles. This helps keep the final
CSS file small and optimized.
2. Theme: This key is used to customize the default theme of
Tailwind CSS. You can define your own values for colors, fonts,
spacing, and more.
3. Extend: This key is used inside the theme key to extend the
default theme without completely overriding it. This is useful for
adding additional utilities or modifying existing ones.
4. Plugins: This key allows you to add plugins to Tailwind CSS. Plugins
can add additional utilities, components, or modify the existing
ones. Tailwind CSS has a variety of official plugins, or you can
create your own.
1. Uncontrolled Components
a. If a component is managing its own state and controlling the
behavior on its own then the component will be known as
Uncontrolled component.
b. The parent component will have no power or control over
this component and hence it will be known as an uncontrolled
component.
●In the above example, the <ItemCard /> component does not
control its own state, instead it is controlled by its parent
component <ItemCardList />.
●But with the currently implemented code, we can not change the
state by clicking the button because the parent component has no
way to know about the user's interaction with the button.
●To do that, we need to let the parent component know when the
button is clicked so that it can change the value of the state
variable i.e. showHeading .
This
● can be achieved by lifting the state up .
●In the below example, we pass a function as a prop i.e. onShow to
the child component i.e. <ItemCard /> from the parent component
i.e. <ItemCardList /> which sets the value of the state variable
showHeading .
●In the child component, we use the onShow prop and pass it as a
function to the onClick event in the button element.
●This will let the parent component know that the user has clicked
the button. Then the value of the showHeading state variable will
be changed.
74
Note - React has a one-way data stream. That means the data flows
into one direction i.e. from parent component to child component.
Props Drilling
Introduction
Redux is not the only library for state management. There is also
another library named Zustand .
Just like we have React Dev Tools, we also have Redux Dev Tools which
help us to debug our application when we use Redux.
There are 2 libraries that Redux team offers:
Redux Store is like a very big JavaScript object, which has a lot of
data in it, stored in a global central space.
Is it a good idea to store all the data in one place ? Yes
80
Redux says that we cannot directly modify the data in the slice. Redux
offers a way to do that.
Assume that we have a cartSlice which keeps track of the data in the
cart. We have an Add to cart button which adds the item into the cart.
By clicking on this button, we cannot directly modify our cartSlice.
To modify the cartSlice, when the user clicks on the Add To Cart
button, we have to dispatch an action .
When we dispatch an action, it calls a function and then this function
modifies the cart .
Here is the flow:
User clicks the button —> Dispatch an action —> Action calls a
function —> Function modifies the cart slice
The function which is being called by the action is known as
Reducer Function .
81
So when the user clicks the button, it dispatches an action. This action
calls the reducer function and this reducer function updates the slice.
********This was about writing the data into the store.**********
Install Redux
Create a slice
●The reducer key is assigned with an object which will have all the
slices (cartSlice in this case).
●The reducer contains the slices where each of the slices contains
its own reducer functions.
●We can subscribe to the store using a selector to read the data
of the store.
●Redux offers a hook named useSelector which can be used to
subscribe to the store.
85
Dispatch an action
●{
Payload: “apple”,
}
●The handleAddItem will be responsible for dispatching the action
and it is assigned to the click event of the button. So whenever
the user clicks the button, the addItem action will be dispatched
and it will add that item to the cart.
1. onClick={handleAddItem}
a. This syntax assigns the handleAddItem function directly to
the onClick event.
b. When the button is clicked, the handleAddItem function will
be called without any arguments.
2. onClick={() => handleAddItem(item)}
a. This syntax uses an arrow function to call handleAddItem
with the item argument.
b. This is useful when you need to pass specific arguments to
the handleAddItem function when the button is clicked.
c. Here, the item needs to be defined or in scope when the
button is rendered.
d. If item is a variable available in the component’s context, it
will be passed to handleAddItem when the button is clicked.
3. onClick={handleAddItem(item)}
a. This syntax is incorrect and will not work as expected.
88
In older redux (vanilla redux), it was not allowed to mutate the state.
We used to create a copy of our state and then modify that. We also
had to return the new state.
This whole process is still done by Redux behind the scenes but now it
is not asking developers to do it. Redux is using the immer library to do
it.
In the new redux, we have to mutate the state. And it is not mandatory
to return the state as well.
89
Types of Testing
●Unit Testing
● Integration Testing
● End-to-End Testing (e2e testing)
1. Unit Testing
a. Unit Testing is a fundamental aspect of software testing
where individual components or functions of an application
are tested in isolation .
b. This method ensures that each unit of the application
performs as expected.
c. By focusing on small, manageable parts of the application,
unit testing helps identify and fix bugs early in the
development process, significantly improving code quality
and reliability.
d. Unit tests are typically automated and written by
developers.
2. Integration Testing
a. Integration testing is a software testing process where
software components, modules, or units are tested to
evaluate system compliance concerning functional
requirements.
90
Install Jest
***************************************************************
We are using parcel and parcel uses babel. So Parcel has its own
configuration of babel already.
When we created babel.config.js, we were creating our own
configuration of babel which conflicts with the existing configuration
of babel.
Configure Jest
1. Would you like to use TypeScript for the configuration file? -> no
(in this case)
2. Choose the test environment that will be used for testing ->
jsdom (browser-like)
a. JSDOM is a library which parses and interacts with
assembled HTML just like a browser.
b. When we run test cases, we do not run them on the browser.
But we need a browser-like environment to run them.
c. JSDOM helps us to get a browser-like environment. It will
give us the features of a browser.
3. Do you want to add coverage reports? -> Yes
4. Which provider should be used to instrument code for coverage?
-> Babel
5. Automatically clear mock calls, instances, contexts and results
before every test? -> Yes
Install jest-environment-jsdom
Basics of Testing
Approach 1: Create a folder named __tests__ . Jest will track all the
files from this folder and execute the test cases. Jest will consider all
the files in this folder as test files .
Approach 2: Suppose we have a file sum.js . If the name of the file in
which you have written test cases matches any of the below filenames,
then it will be considered as a test file.
1. sum.test.js
2. sum.test.ts
3. sum.spec.js
4. sum.spec.ts
94
● Then we can run our command npm run test to test the
component. When we do that, we will get the below error:
This error says that we can not use JSX inside our test case. JSX
isn’t enabled for our test cases. The error also says that to make
the JSX work, we have to add @babel/preset-react.
Install @babel/preset-react
Now when we run the command npm run test, this time our test
cases will be passed.
98
●We use getAllByRole() method to get all the elements which have
the specified role.
●We have specified the role as textbox to get the input elements.
●When we do console.log(inputName) , it prints the array of React
elements (objects/JSX) . These React elements are the input
elements we have in our document.
●Then we want to make sure that there should be 2 input elements.
Hence we expect the length of inputName to be 2.
●We can group all the test cases in a file using the describe()
function.
●This function takes 2 arguments:
○Description
○An arrow function
●Inside the arrow function, we can put all the test cases.
●We can also create groups inside a group. To do that, we can put a
describe function inside a describe function.
102
Note: We can also change the name of function test() to it(). They
both work the same way. it() is like an alias of test().
103
●Consider that the <Header /> component also uses the <Link> tag
from react-router-dom to allow user to navigate from one page to
another.
●The test() or it() function also does not know about <Link>
element because it is not part of React but React router dom.
●So in order to make it work, we have to import the
BrowserRouter from react-router-dom and wrap our <Header />
component inside it.
● These props will be the mock data which we will create inside a
folder named as mocks .
● So create a folder named as mocks . Then create a file inside it
and name it as itemCardMock.json .
107
Integration Testing
●When we run the npm run test command, it gives an error: fetch
is not defined.
●This error occurs because fetch() given by browser and we are
rendering this <Body> component on JSDOM which is browser-like
but not the actual browser.
●Hence this super power of browser i.e. fetch() does not exist on
JSDOM. So we have to create a mock function the same way we
created the mock data.
Note: A test case does not make an actual API call. Because we do
not run it on the browser, so it does not have power to talk to the
world.
Note: Currently, we have to run the npm run test command again
and again after creating test cases. To solve that issue, we can
add a new command in the package.json file inside our scripts .
And instead of using npm run test command, we can use npm run
watch-test .
109
●For the change event, browser gives the event object which has a
target value. But to test this feature, we can give the mock data
i.e. Jeans .
●Then we fire a click event on the search button.
●Then we find the cards using their test id i.e. ItemCard .
●And we expect to have 3 results when we search for Jeans.
Helper functions
useMemo
●This is when we should use the useMemo hook. The useMemo hook
memoize the calculation result.
●useMemo() hook takes 2 arguments:
○Acallback function
○Adependency array
●Callback function performs the calculation.
●And useMemo hook performs the operation only when there is a
change in the dependency array.
●So even if all the state variables are changed in the component,
but there is not change in the dependency array, then the
calculation will not be performed again.
useCallback
useRef