Assignments of NamasteReact Course ?
Assignments of NamasteReact Course ?
Assignment 01 - Inception
Owner Pankaj Kumar
1: What is Emmet?
Emmet is the essential toolkit for web-developers. It allows you to type shortcuts
that are then expanded into full pieces of code for writing HTML, XML, CSS and Other
languages based on an abbreviation structure most developers already use that
In Visual Studio Code (VS Code), Emmet is built-in and can be accessed by
typing abbreviations and then pressing the Tab key to expand them.
For example, typing "div.container" and pressing Tab will expand to:
<div class="container"></div>
One key difference between libraries and frameworks is that libraries are called
by the code, while frameworks call the code. In other words, when you use a
library, you are in control of how and when it is used. With a framework, the
framework is in control and dictates how the code should be organized and
used.
Assignment 01 - Inception 1
What_is_a_CDN__.pdf
(OR)
CDN(Content Delivery Network) are used by a wide range of websites and
applications, including e-commerce sites, media and entertainment platforms,
and software as a service (SaaS) providers.
Improving the speed of web pages: By serving content from a server that is
physically closer to the user, CDNs can significantly improve the loading speed
of web pages.
The purpose of crossorigin attribute is used to share the resources from one
domain to another domain. Basically, it is used to handle the CORS request. It is
Assignment 01 - Inception 2
used to handle the CORS request that checks whether it is safe to allow for
sharing the resources from other domains.
Syntax
<script crossorigin="anonymous|use-credentials">
You can think of these as the isomorphic or universal helpers that you need to
build components. The react-dom package contains ReactDOM.render() , and in
react-dom/server we have server-side rendering support with
ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup() .
Assignment 01 - Inception 3
7: What is difference between react.development.js
and react.production.js files via CDN?
Development is the stage of an application before it's made public while
production is the term used for the same application when it is made public.
The production build, on the other hand, runs in production mode which means
this is the code running on your client’s machine.
Development build is several times (maybe 3-5x) slower than the production
build.
available (do not block HTML DOM construction during downloading process) and
don’t wait for anything.
Syntax
finished parsing(when browser finished DOM construction). The defer attribute tells
the browser not to wait for the script . Instead, the browser will continue to process
the HTML, build DOM.
Syntax
Assignment 01 - Inception 4
🚀
Assignment 02 - Igniting Our App
Owner Pankaj Kumar
1: What is NPM?
It is a tool used for package management and the default package manager for
Node projects. NPM is installed when NodeJS is installed on a machine. It comes
with a command-line interface (CLI) used to interact with the online database of
NPM. This database is called the NPM Registry , and it hosts public and private
'packages.' T o add or update packages, we use the NPM CLI to interact with this
database.
Note : npm does not stand for node package manager but everything else.
npm init
npm init -y can be used to skip the setup step, npm takes care of it and creates the
Both of these bundlers substantially reduce the time it takes for the transfer of data
and files to the server from the application.
Along with that both bundlers parcel and webpack remove the unnecessary
comments, new lines, any kind of block delimiters, and white spaces while the
functionality of the code remains unchanged.
It offers blazing fast performance utilizing multicore processing, and requires zero
configuration. Parcel can take any type of file as an entry point, but an HTML or
JavaScript file is a good place to start.
Parcel Features:
HMR (Hot Module Replacement) —> parcel keeps track of file changes via file
watcher algorithm and renders the changes in the files
Minification
Image optimization
Compresses
HTTPS in dev
Port Number
installation commands:
Parcel Commands :
3: What is .parcel-cache
.parcel-cache is used by parcel(bundler) to reduce the building time.
It stores information about your project when parcel builds it, so that when it
rebuilds, it doesn't have to re-parse and re-analyze everything from scratch. It's a
key reason why parcel can be so fast in development mode.
The dist folder contains the output of Parcel and the content of that folder is served
by the web server.
4: What is npx ?
The npx stands for Node Package Execute. It is a tool that is used to execute the
packages. It comes with the npm, when you installed npm above 5.2.0 version then
automatically npx will be installed. It is an npm package runner that can execute any
If the package is only to be used once or twice, rather than every time the project
runs, it is preferable to utilize NPX, which will execute the package without installing
it.
instead of just,
“You can imagine your application as a tree. The source code and libraries you
actually use represent the green, living leaves of the tree. Dead code represents the
brown, dead leaves of the tree that are consumed by autumn. In order to get rid of
the dead leaves, you have to shake the tree, causing them to fall.”
This can significantly speed up development in a few ways: Retain application state
which is lost during a full reload.
HMR is enabled for the dev server. When you change your files and save them, the
HMR will automatically change your contents without recompile and reload whole
project.
HMR is the same as Live Reload with the difference that it only replaces the
modules that have been modified, hence the word Replacement.
The advantage of this is that it doesn't lose your app state e.g. your inputs on your
form fields, your currently selected tab etc.
File watcher algorithm: File Watchers monitor directories on the file system and
perform specific actions when desired files appear.
Automatic production optimization: Parcel optimizes your whole app for production
automatically. This includes tree-shaking and minifying your JavaScript, CSS, and
Ship for any target: Parcel automatically transforms your code for your target
environments. From modern and legacy browser support, to zero config JSX and
TypeScript compilation, Parcel makes it easy to build for any target or many!
Scalable: Parcel requires zero configuration to get started. But as your application
grows and your build requirements become more complex, it's possible to extend
Parcel in just about every way. A simple configuration format and powerful plugin
system that's designed from the ground up for performance means Parcel can
support projects of any size.
A gitignore file specifies intentionally untracked files that Git should ignore. Files
already tracked by Git are not affected. The .gitignore file is a text file that tells Git
which files or folders to ignore in a project during commit to the repository.
The types of files you should consider adding to a .gitignore file are any files that do
not need to get committed. for example, For security, the security key files and API
keys should get added to the gitignore.
Note: package-lock.json should not add into your .gitignore file.
You should not commit these four types of files into your Git repository.
Credentials
The file resides in the root directory of every Node. js package and appears
after running the npm init command.
The package. json file contains descriptive and functional metadata about a
project, such as a name, version, and dependencies.
package-lock.json :
This file is automatically generated for those operations where npm modifies
either the node_module tree or package-json.
The “package. json” file defines the rules required to run your application and
install dependencies. On the other hand, the “package-lock. json” file holds
It is generated after an npm install and not designed to be manually edited and
we should not delete it either.
As name suggests, lock. json is created for locking the dependency with the
installed version. It will install the exact latest version of that package in your
application and save it in package.
It allows future devs & automated systems to download the same dependencies
as the project.
it also allows to go back to the past version of the dependencies without actual
committing the node_modules folder.
It records the same version of the installed packages which allows to reinstall
them. Future installs wll be capable of building identical description tree.
~ or ^ in package.json file :
These are used with the versions of the package installed.
For example in package.json file:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
^ : “Compatible with version”, will update you to all future minor/patch versions,
without incrementing the major version.
eg. ^2.3.4 will use releases from 2.3.4 to <3.0.0.
When you npm install them, they are downloaded from the web and copied into the
node_modules folder and Nodejs is trained to look for them there when you import
them (without a specific path).
we should not push node_modules in github because it contains lots of files(more than
100 MB), it will cost you memory space.
The /dist folder contains the minimized version of the source code.
The code present in the /dist folder is actually the code which is used on production
web applications.
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.
It is easier to add files to the /dist folder as it is an automatic process. All the files
are automatically copied to the dist folder on save.
The /dist folder also contains all those files which are required to run/build a module
for use with other platforms- either directly in the browser, or in an AMD system (eg.
require.js).
Ideally, it is considered a good practice to clean the /dist folder before each build.
"browserslist": [
"last 3 versions"
]
This means my parcel will make sure that my app works in last 3 versions of
all the browsers available.
Browserslist helps you keep the right balance between browser compatibility and
bundle size. With Browserslist, you will cover wider audience and have smaller
bundle size.
1: What is JSX ?
JSX is a syntax extension to JavaScript. It is a HTML-like syntax (but not HTML) in
javascript.
JSX converts HTML tags into react elements, it easier to write and add HTML in
React.
JSX allows us to write HTML elements in JavaScript and place them in the DOM
without any createElement() and/or appendChild() methods.
After compilation, JSX expressions become regular JavaScript function calls and
evaluate to JavaScript objects.
const element = (
<h1 className="greeting">
Hello, world - With JSX!
</h1>
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);
2: Superpowers of JSX .
JSX allows us to write HTML-Like(not HTML) syntax in JavaScript.
JSX is very secure & makes sure that the app is safe.
JSX Prevents Injection Attacks : This is safe. {} —> acts like a sanitiser.
Example
Note: In this example, by default, React DOM escapes any values embedded in JSX
before rendering them. Thus it ensures that you can never inject anything that’s not
explicitly written in your application. Everything is converted to a string before being
rendered. This helps prevent XSS (cross-site-scripting) attacks.
Syntax
<script type="text/javascript"></script>
text/ecmascript : this value indicates that the script is following the EcmaScript
standards.
module : This value tells the browser that the script is a module that can import or
export other files or modules inside it.
text/babel : This value indicates that the script is a babel type and required bable to
transpile it.
4: {TitleComponent} vs {<TitleComponent/>} vs
{<TitleComponent></TitleComponent>} in JSX .
A: The Difference is stated below:
Some JSX value. In simple terms TitleComponent a function that is returning a JSX
value.
A component is written inside the {< />} expression.
components. The opening and closing tags are created to include the child
components.
<TitleComponent>
<FirstChildComponent />
<SecondChildComponent />
<ThirdChildComponent />
</TitleComponent>
Tree-shaking is an important way to reduce the size of your bundle and improve
performance.
It depends on the static syntax of import and export modules in ES6 (ES2015). By
taking tree-shaking concepts into consideration when writing code, we can
significantly scale down the bundle size by getting rid of unused JavaScript, thereby
optimizing the application and increasing its performance.
Unlike browser DOM elements, React elements are plain objects, and are cheap to
create. React DOM takes care of updating the DOM to match the React elements.
Using React without JSX is especially convenient when you don’t want to set up
compilation in your build environment.
So, anything you can do with JSX can also be done with just plain JavaScript.
Example of JSX
ES6 is the standardization of javascript for making code more readable and more
accessible.
The latest projects created on React rely a lot on ES6. React uses ES6, and you
should be familiar with some of the new features like: Classes, Arrow Functions,
Variables(let, const).
ES6 is the standardization of javascript for making code more readable and more
accessible.
3: {TitleComponent} vs {<TitleComponent/>} vs
{<TitleComponent></TitleComponent>} in JSX .
{TitleComponent} : This value describes the TitleComponent as a javascript expression
or a variable.
The {} can embed a javascript expression or a variable inside it.
Some JSX value. In simple terms TitleComponent a function that is returning a JSX
value.
A component is written inside the {< />} expression.
components. The opening and closing tags are created to include the child
components.
Example
<TitleComponent>
<FirstChildComponent />
<SecondChildComponent />
<ThirdChildComponent />
</TitleComponent>
Example
Fragments let you group a list of children without adding extra nodes to the DOM.
The only difference between them is that the shorthand version does not support
the key attribute.
Example
return (
<React.Fragment>
<Header />
<Body />
<Footer />
</React.Fragment>
);
------------ OR --------------
return (
<>
<Header />
<Main />
<Footer />
</>
);
React uses a virtual DOM (Document Object Model) to update the UI. The virtual
DOM is a lightweight in-memory representation of the real DOM, which allows
React to make changes to the UI without manipulating the actual DOM. This makes
updates faster, as changing the virtual DOM is less expensive than changing the
real DOM.
The reconciliation algorithm works by comparing the current virtual DOM tree to the
updated virtual DOM tree, and making the minimum number of changes necessary
to bring the virtual DOM in line with the updated state.
Tree diffing: React compares the current virtual DOM tree with the updated
virtual DOM tree, and identifies the minimum number of changes necessary to
bring the virtual DOM in line with the updated state.
Batching: React batches multiple changes into a single update, reducing the
number of updates to the virtual DOM and, in turn, the real DOM.
The reconciliation algorithm is a critical part of React’s performance and helps make
React one of the fastest and most efficient JavaScript libraries for building user
interfaces.
After the reconciler compares the current and updated virtual DOM, it identifies the
differences and makes the necessary changes to the virtual DOM to bring it in line
with the updated state.
React Fiber is a backwards compatible, complete rewrite of the React core. In other
words, it is a reimplementation of older versions of the React reconciler.
Introduced from React 16, Fiber Reconciler is the new reconciliation algorithm in
React.
Fiber allows the reconciliation and rendering to the DOM to be split into two
separate phases: Phase 1: Reconciliation and Phase 2: Commit.
Increases the suitability of the React library to create animations, layouts, and
gestures.
Keys helps React identify which items in the list have changed, are added, or are
removed.
In other words, we can say that keys are unique Identifier used to give an identity to
the elements in the lists.
The best way to pick a key is to use a string that uniquely identifies a list item
among its siblings.
When you don’t have stable IDs for rendered items, you may use the item index as
a key as a last resort.
Example
Recursing On Children
By default, when recursing on the children of a DOM node, React just iterates over both
lists of children at the same time and generates a mutation whenever there’s a
difference.
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
React will match the two <li>first</li> trees, match the two <li>second</li> trees, and
then insert the <li>third</li> tree.
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>
React will mutate every child instead of realizing it can keep the <li>Duke</li> and
<li>Villanova</li> subtrees intact. This inefficiency can be a problem.
In order to solve this issue, React supports a key attribute. When children have keys,
React uses the key to match children in the original tree with children in the subsequent
tree. For example, adding a key to our inefficient example above can make the tree
conversion efficient:
<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
Now React knows that the element with key '2014' is the new one, and the elements
with the keys '2015' and '2016' have just moved.
Props stand for "Properties." They are read-only components. It is an object which
stores the value of attributes of a tag and work similar to the HTML attributes. It
gives a way to pass data from one component to other components. It is similar to
function arguments. Props are passed to the component in the same way as
arguments passed in a function.
Props are immutable so we cannot modify the props from inside the component.
Inside the components, we can add attributes called props. These attributes are
available in the component as props and can be used to render dynamic data in our
render method.
Props are used to store data that can be accessed by the children of a React
component. They are part of the concept of reusability. Props take the place of class
attributes and allow you to create consistent interfaces across the component
hierarchy.
Every parent component can pass some information to its child components by giving
them props. Props are similar to HTML attributes, but you can pass any JavaScript
value through them, including objects, arrays, and functions.
Types of Props :
Familar Props ——> HTML attributes like className, src, width, height passed in
HTML tag
Passing Props to Component ——> props are the only argument to your
component. React component functions accept a single argument, a props object.
However, props are immutable which means unchangeable. When a component needs
to change its props (for example, in response to a user interaction or new data), it will
have to “ask” its parent component to pass it different props—a new object! Its old props
will then be cast aside, and eventually the JavaScript engine will reclaim the memory
taken by them.
Config Driven UI are based on the configurations of the data application receives. It
is rather a good practice to use config driven UIs to make application for dynamic.
It is a very common & basic approach to interact with the User. It provides a generic
interface to develop things which help your project scale well. It saves a lot of
development time and effort.
Config driven UI not only make your code cleaner but also easier to maintain.
You can any time change/add the validations in the config (Like maxValue , or add a
regex pattern, etc.. ) and change the renderer function to accept those keys.
Virtual DOM
The Virtual DOM is a light-weight abstraction of the DOM. You can think of it as
a copy of the DOM, that can be updated without affecting the actual DOM. It
has all the same properties as the real DOM object, but doesn’t have the ability
to write to the screen like the real DOM.
Virtual DOM is just like a blueprint of a machine, can do the changes in the
blueprint but those changes will not directly apply to the machine.
Reconciliation is a process to compare and keep in sync the two files (Real and
Virtual DOM). Diff algorithm is a technique of reconciliation which is used by
React.
Real DOM
The DOM represents the web page often called a document with a logical tree
and each branch of the tree ends in a node and each node contains object
programmers can modify the content of the document using a scripting
Creates a new DOM if the element updates Update the JSX if the element update
It allows us to directly target any specific node It can produce about 200,000 Virtual DOM
(HTML element) Nodes / Second
export <function>;
<Module.Comp1 />
<Module.Comp2 />
<Module.Comp3 />
useState is a React Hook that lets you add a state variable to your component.
const [state, setState] = useState(initialState);
is a React Hook that lets you read and subscribe to context from
useContext
your component.
const value = useContext(SomeContext)
useReducer is a React Hook that lets you add a reducer to your component.
useMemois a React Hook that lets you cache the result of a calculation between
re-renders.
(OR) It returns a memoized value that helps in performance optimizations.
const cachedValue = useCallback(calculateValue, dependencies)
useCallback is a React Hook that lets you cache a function definition between
re-renders.
const cachedFn = useCallback(fn, dependencies)
useRefis a React Hook that lets you reference a value that’s not needed for
rendering.
const ref = useRef(initialValue)
(OR) It returns a ref object with a current property. The ref object is mutable. It is
mainly used to access a child component imperatively.
(OR) It fires at the end of all DOM mutations. It's best to use useEffect as much
as possible over this one as the useLayoutEffect fires synchronously.
React DevTools.
useDebugValue(value, format?)
accessibility attributes.
const id = useId()
useTransition is a React Hook that lets you update the state without blocking
the UI.
const [isPending, startTransition] = useTransition()
1: What is Microservice ?
Microservice - also known as the microservice architecture - is an architectural
method that relies on a series of Independently deployable services. These services
have their own business logic and database with a specific goal. Updating, testing,
deployment, and scaling occur within each service. Microservices decouple major
Benefits of Microservices:
Easier to Test
Flexible Scaling
Easy Deployment
Technological Freedom
Reusable Code
Resilience
that couples all of the business concerns together . To make a change or a small
change in it (We need to deploy the hole project init.For instance we changed a
button we use deploy our Whole project.) to this sort of application requires updating
the entire stack by accessing the code base and building and deploying an updated version
of the service-side interface. This makes updates restrictive and time-consuming.
3. Performance In a centralized code base and repository, one API can often
perform the same function that numerous APIs perform with microservices.
useEffect accepts two arguments , first is a callback function and a dependency array .
The second argument is optional.
Syntax
`useEffect(() => {}, [])`
useEffect(() => {
setCurrentState("true");
}, [currentState])
If we do not pass empty dependency array then the useEffect runs everytime when
the UI is rendered.
Optional Chaining ( ?. ) is good way of accessing the object keys, it prevents the
application from being crashed if the key that we are trying to access is not present.
If the key is not present then instead of a throwing key error, it returns undefined .
6: What is Shimmer UI ?
A shimmer screen is a version of the UI that doesn’t contain actual content. Instead,
it mimics the page’s layout by showing its elements in a shape similar to the actual
A shimmer screen is essentially a wireframe of the page, with placeholder boxes for
text and images.
3. if(true){
console.log("true");
} else {
console.log("true");
} ----> This does not return any value
Having said that, we can't put any js code inside {} in jsx of React. Only js
In the above example, we are creating a state variable that is initially set to false,
since our data has not been loaded in our application yet.
Untill our data is loaded completely we can show a shimmer UI to the user and when
our data gets loaded we can render the data on the page. The conditional rendering
is done via a ternery operator ?: for example :
In the above expression, if isLoaded is set to false then, Shimmer component will be
loaded , when the data loading is completed, the Body component will be rendered.
&&operator : if the condition is true, display the right-side code else display
nothing.
{ errorMsg && {errorMsg} }
9: What is CORS ?
CORS stands for Cross Origin Resource Sharing , It is a HTTP-header based
machanism that allows a server to indicate any origin other that it's own. We can
create requests to other domains or ports to get the data from our browser.
async function always returns a promise, any values are automatically wrapped
inside a resolved promise.
await: Await function is used to wait for the promise to be settled. It could be used
within the ‘async` block only. It makes the code wait until the promise returns a
result. It only makes the async block wait.
For example : Let's try to write a function getRestaurants() to fetch restaurant data
from a public API.
First, let's try to write it with Promise chaining : fetch(url) returns a promise (resolve or
reject), which can be consumed by the then (success) handler or catch (error)
handler
function getRestaurants() {
fetch(url).then((data)=>{data.json()})
.then((json)=>{
console.log(json);
}).catch((err)=>{
console.log(err);
})
}
Using async and await : await waits until fetch(url) returns a promise with the data
and headers which again needs to be resolved using .json() method to get the data.
If any of promise inside try block is rejected, the control jumps to catch block.
the data or response. The method returns a promise because we have used await
keyword.
so data.json() returns a promise resolved to a JSON object .
Adding the image into the project Drag your image into your project and import it
into the desired component
4: What is SPA?
is a web application that dynamically updates the
Single Page Application (SPA)
webpage with data from web server without reloading/refreshing the entire page. All
the HTML, CSS, JS are retrieved in the initial load and other data/resources can be
loaded dynamically whenever required. An SPA is sometimes referred to as a single-
page interface (SPI) .
Example : Facebook is a Single Page Application which loads lot of components and
refreshes only the required component.
2. Make a network call, get HTML, CSS, JS and loads the whole page.
In Client-side routing or rendering (CSR) , during the first load, the webapp is
loaded from server to client, after which whenever there is a change in URL, the
router library navigates the user to the new page without sending any request to
backend(don’t do full page reload). All Single Page Applications uses client-side
routing .
Now we can create a nested routing for /path using children again as follows:
1. constructor()
2. render ()
3. componentDidMount()
4. componentDidUpdate()
5. componentWillUnmount()
Explanation:-
These methods are called in the following order when an instance of a component
is being created and inserted into the DOM:
Mounting :
Constructor is the only place where you should assign this.state directly. In all other
methods, you need to use this.setState() instead.
async componentDidMount() {
//This is the best place we make an API call
const data = await fetch("https://api.github.com/users/sam-0905");
const json = await data.json();s
this.setState({
userInfo: json,
});
console.log("userInfo", json);
console.log("componentDidMount");
}
6: (Research) Why do we
use super(props) in constructor ?
is used to inherit the properties and access of variables of the React parent
super(props)
A component that extends React.Component must call the super() constructor in the
derived class since it’s required to access this context inside the derived class
constructor.
When you try to use props passed on parent to child component in child component
using this.props.name , it will still work without super(props). Only super() is also enought
for accessing props in render method.
The main difference between super() and super(props) is the this.props is undefined in
child's constructor in super() but this.props contains the passed props if super(props) is
used.
Solution to this is not making the callback function async but created another async
function inside callback function of useEffect().
The lazy() function is typically used in scenarios where you have large or less
frequently used components that you want to load `asynchronously`.
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
</div>
);
}
The fallback prop accepts any React elements that you want to render while waiting
for the component to load. You can place the Suspense component anywhere
above the lazy component. You can even wrap multiple lazy components with
a single Suspense component.
Data fetching: If your application needs to fetch data from an API or perform
asynchronous operations, Suspense can be used to handle the loading state and
display fallback content until the data is available. This simplifies the management
of loading states and ensures a smooth transition between loading and displaying
the data.
Code splitting: Code splitting involves breaking your application's code into smaller
chunks that can be loaded separately. When using dynamic imports and code
splitting techniques, Suspense can be used to wrap the components that are being
lazily loaded. It allows you to provide fallback content while the code chunks are
being fetched and loaded, improving the perceived performance of your application.
1. Writing normal Nativice CSS : By creating .css files and adding them to
our html files
1. content : This configuration of the file formats, on which the styles are applied.
e.g.
content: [
"./src/**/*.{html,js,ts,jsx,tsx}",
],
This configuration means that in files extensions of html , js, ts ,tsx, jsx files will
use the stylings of Tailwind.
2. theme : Theme is where we design our own custom configurations for our project
like colors and font-families for our application.
module.exports = {
theme: {
screens: {
sm: '480px',
md: '768px',
lg: '976px',
xl: '1440px',
},
colors: {
'blue': '#1fb6ff',
'purple': '#7e5bef',
'pink': '#ff49db',
},
}
}
3. extend: Here we can extend more properties for Tailwind like adding values that
does not exist for tailwind or overriding the existing the values for tailwind.
extend: {
spacing: {
'128': '32rem',
4. plugins : We can use to inject new style in our project using JavaScript instead of
css.
const plugin = require('tailwindcss/plugin')
module.exports = {
plugins: [
plugin(function({ addUtilities, addComponents, e, config }) {
// Add your custom styles here
}),
]
}
```
import React from 'react';
import ChildComponentA from './ChildComponentA';
const ParentComponent = () => {
const data = "Hello, Prop Drilling!";
return (
<div>
<ChildComponentA data={data} />
</div>
);
};
```
```
// ChildComponentA.js
```
// ChildComponentB.js
import React from 'react';
import ChildComponentC from './ChildComponentC';
const ChildComponentB = ({ data }) => {
return (
<div>
<ChildComponentC data={data} />
</div>
);
};
export default ChildComponentB;
```
```
// ChildComponentC.js
import React from 'react';
const ChildComponentC = ({ data }) => {
return <div>{data}</div>;
};
export default ChildComponentC;
```
In this example, the data prop is passed from the ParentComponent down to
ChildComponentA, then from ChildComponentA down to ChildComponentB, and finally
from ChildComponentB to ChildComponentC. This pattern continues if we need to pass
the data further down to more child components.
```
// ParentComponent.js
import React, { useState } from 'react';
import ChildComponentA from './ChildComponentA';
import ChildComponentB from './ChildComponentB';
const ParentComponent = () => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<ChildComponentA count={count} incrementCount={incrementCount} />
<ChildComponentB count={count} />
</div>
);
};
export default ParentComponent;
```
```
// ChildComponentA.js
import React from 'react';
const ChildComponentA = ({ count, incrementCount }) => {
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
};
export default ChildComponentA;
```
```
// ChildComponentB.js
import React from 'react';
const ChildComponentB = ({ count }) => {
return (
<div>
In this example, the state variable count and the function incrementCount are
declared in the ParentComponent, which serves as the common parent for
ChildComponentA and ChildComponentB. The count state is lifted up to
ParentComponent and passed down as a prop to both ChildComponentA and
ChildComponentB. When ChildComponentA increments the count using the
incrementCount function, the updated count will be reflected in both
ChildComponentA and ChildComponentB, as they share the same state.
Lifting the state up promotes better data flow, simplifies state management, and
helps to avoid inconsistencies in the application state. It is particularly useful when
components need to interact with each other or when multiple components depend
on the same data source.
For example:
return (
<UserContext.Provider value={{ user: user, setUser: setUser }}>
<Head />
<Outlet />
<Footer />
</UserContext.Provider>
);
In the code above , we are providing the access of UserContext to <Head /> <Outlet
/> and <Footer /> component
2. Context Consumeris used to consume the context data , provided by react context.
We can do this using useContext hook for functional components
For example:
In Class based components, we can use the Context and use the consumer.
<UserContext.Consumer>
{({ user }) => <h1>{user.name}</h1>}
</UserContext.Consumer>
1: useContext vs Redux.
Both usecontext and redux are used to solve props drilling , a problem faced while
passing props between components.
conveniences on top of regular Redux, which make it easier to work with and
manage the state of your application. This includes features such as
time you make an update, which can become repetitive and error-prone. Redux
Toolkit provides a way to update the state immutably , using its built-
in createSlice function.
become complex and difficult to manage as your application grows. With Redux
Toolkit, you can use the createSlice function to generate reducers for you, based on
the state updates you define.
5. Better Debugging: Redux Toolkit provides better debugging tools, such as the ability
to log and replay actions, inspect the current state of your application, and easily
track the changes made to your state over time.
3: Explain Dispatcher.
A dispatcher is a function that dispatches actions to the store. In Redux, actions are
used to describe changes to the state, and dispatching an action is the way to trigger
those changes.
This hook returns a reference to the dispatch function from the Redux store. You may
use it to dispatch actions as needed.
action creator and which in turns calls the reducer function to trigger the update.
4: Explain Reducer.
A reducer is a pure function in Redux that takes the current state of your application
and an action , and returns a new state based on that action .
Example :
Here based on the action object, the state is updated inside teh reducer function.
5: Explain slice.
In Redux Toolkit, a slice is a piece of the state that is managed by a single set of
actions and reducer.
6: Explain selector.
A selector is a pure function that takes the current state of your application and
returns a derived value based on that state.
useSelector is a hook from the react-redux library that allows you to subscribe to
the state of your Redux store from a React component. The useSelector hook takes
a selector function as its argument, which is used to extract data from the state tree.
The component will re-render whenever the state of your Redux store changes and the
derived value returned by the selector function changes.
The createSlice function takes an object as an argument, which contains the following
properties:
initialState: An object that represents the initial state of the slice. In our
cartSlice example, the initial state is an object with two properties: items (an empty
object) and totalItemsCount (which is 0).
reducers: An object that contains the Redux reducers for the slice. Reducers are
functions that take the current state and an action , and return a new state based
on the action type and payload. In our example, there are three reducers: addItem,
removeItem, and clearCart.
After creating the slice, the code exports the actions that can be dispatched on the
store. In this example, there are three actions: addItem, removeItem, and clearCart.
Finally, the code exports the reducer for the slice using the reducer property of the
slice. The reducer is responsible for managing the state of the slice and updating it in
response to dispatched actions.
End-to-end Testing: tests the entire system, from start to finish, simulating real-world
scenarios.
Performance Testing: tests the performance of the software, such as response time,
scalability, and stability under different load conditions.
Security Testing: tests the security of the software, verifying it is protected against
potential threats and vulnerabilities.
Regression Testing:tests the software after changes have been made, ensuring the
changes did not introduce new bugs or break existing functionality.
Smoke Testing:a preliminary test to determine if the basic functions of the software
work, before proceeding with more thorough testing.
Jest is a popular and widely used testing framework for JavaScript applications due to
the following reasons :
2. Speed: fast test execution, automatic test caching, parallel test running
3. Integration: integrates well with popular JavaScript tools and frameworks, such as
React, Babel, and Webpack.