JavaScript notes
JavaScript notes
Syllabus
========
-ReactJs features (VirtualDOM , ReConciliation)
-Local Environemnt Setup
-Create-react-app
-JSX
-Class Components
-Functional Components
-React Object - Fragment
-Component Styling
-Conditional rendering
-Lists & keys
-Props : de-structuring,requiring props,
proptypes,default props
-State :
-Pure Component
-Memo Component
-HigherOrder Component
-Events : Synthetic Event
-Lifecycle Hooks
-Form
-Http - Axios
-Interceptors
-Routing
-REDUX (State Management)
-Unit Testing (JEST)
-EsLint
LEASE AGREEMENT
create-react-app
================
-It is a React application boilerplate generator
created by Facebook.
LEASE AGREEMENT
-This CLI tool installs React,ReactDOM & other
libraries required for a react project.
-It provides a development environment configured
for ease-of-use with minimal setup.
-It creates a frontend build pipeline. Under the
hood, it uses Babel and webpack.
NPX
===
-NPX : node package executer.
-Its a Package runner/executer tool.
-It can execute any package that you want from the
npm registry without even installing that package.
ex: npx create-react-app my-app
What React is
=============
-React is a JavaScript library for building user
interfaces.
-It is an open-source, component based library.
-It is created & maintained by Facebook.
-React is used to build single page applications.
-React allows us to create reusable UI components.
LEASE AGREEMENT
-ReactJS uses virtual DOM based mechanism to fill
in data (views) in HTML DOM.
Framework
Library
==================================
LEASE AGREEMENT
==================================
=====
-group of libraries to make your work easier
-performs specific, well-defined operations
-provides ready to use tools,standards
-provides reusable functions for our code
templates for fast application development
-Collection of libraries & APIs
-collection of helper functions,objects
-cann't be easily replaceable
-can be easily replaceable by another
-angular,vue
-jQuery,ReactJs,lodash,moment
-Hospital with full of doctors
-A doctor who specializes in one
React
Angular
==================================
=========================
1. Library-2013
1. Framework-2009
2. Light-weight
LEASE AGREEMENT
2. Heavy
3. JSX + Javascript
3. HTML + Typescript
4. Uni-Directional
4. Two-way
5. Virtual DOM
5. Regular DOM
6. Axios
6. HttpClientModule
7. No
7. Dependency Injection
8. No
8. Form Validation
9. extra libraries needed 9. No
additional libraries
10. UI heavy
10. Functionality Heavy
React Features
==============
-JSX
-Components (easy to build, easy to
extend,reusable,loosly coupled)
-One-way Data Binding (watchers will not be there
LEASE AGREEMENT
for bindings)
-Virtual DOM
-Easy to learn because of its simple Design
-Performance
ReactDOM
========
-ReactDOM is the glue between React and the
DOM.
-React creates a virtual representation of your User
Interface (what we call a Virtual DOM) and then
ReactDOM is the library that efficiently updates the
DOM based on the Virtual DOM.
-The reason why the Virtual DOM exists is to figure
out which parts of the UI need to be updated and
then batch these changes together.
-ReactDOM receives those instructions from React
and then efficiently updates the DOM.
React Reconciliation
====================
-Reconciliation is the process through which React
updates the DOM.
(syncing the Virtual DOM to the actual DOM)
-Reconciliation is the mechanism that tracks
changes in a component state and renders
the updated state to the screen.
-It's a step that happens between the render()
function being called and the displaying of
elements on the screen. This entire process is called
reconciliation.
Fiber Reconciler
================
-Fiber is the new reconciliation engine or
re-implementation of core algorithm in React v16.
-React Fiber reconciler makes it possible to divide
the work into multiple units of work(incremental
LEASE AGREEMENT
rendering).
-It sets the priority of each work, and makes it
possible to pause, reuse, and abort the unit of work.
-Fiber is Asynchronous.
-reconciliation and rendering to the DOM weren't
separated, and React couldn't pause
its traversal to jump to other renders in between.
This often resulted in lagging inputs.
-Fiber allows the reconciliation and rendering to the
DOM to be split into two separate phases:
Phase 1: render(processing)
-----------------------
-React creates a list of all changes to be rendered in
the UI
-Once the list is fully computed, React will schedule
these changes to be executed in the next phase.
-React doesn't make any actual changes in this
phase.
Phase 2: Commit
----------------
-React tells the DOM to render the changes that
was created in the previous phase.
-the Reconciliation phase can be interrupted, the
Commit phase cannot.
LEASE AGREEMENT
React Project - Folder Structure
================================
node_modules/ : Provides npm packages to the
entire workspace. Workspace-wide node_modules
dependencies are visible to all projects.
public/ : Only files inside the `public`
folder can be referenced from the HTML
src/ : Source files for the
root-level application project.
.gitignore : Specifies intentionally
untracked files that Git should ignore.
package.json : Configures npm package
dependencies that are available to all projects in the
workspace.
package-lock.json : Provides version information for
all packages installed into node_modules by the
npm client.
README.md : Introductory
documentation for the application.
root.render(<App />)
where what
3. App.js --> AppComponent Code
JSX
===
-JSX (JavaScript Syntax Extension)is a special syntax
for React that makes it easier to represent the UI.
-JSX is used to describe the structure & content of a
react component.
-JSX allows us to add the elements in DOM without
using createElement() or appendChild() methods.
-JSX looks similar to HTML but it is not HTML.
-JSX code we write gets transformed into
React.createElement().
-JSX is not part of browser. we need a tool(Babel)(a
JavaScript compiler)
to transform it to valid JavaScript.
-JSX doesn't support void tags.
<img> invalid
<img></img> valid
LEASE AGREEMENT
<img /> valid
-Since JSX is closer to JavaScript than to HTML,
React DOM uses camelCase property naming
convention instead of HTML attribute names.
-ex: class becomes className in JSX, and tabindex
becomes tabIndex.
React Element
=============
-A React element is a JavaScript object with specific
properties and methods that React
assigns and uses internally.
-React elements are the instructions for how the
browser DOM get created.
-When we use ReactDOM library React elements are
getting changed into DOM elements.
-However, when we use React Native, React
elements are getting changed into native UI
elements of Android or iOS.
-We create React elements using a function called
createElement().
-createElement() method is part of the Top-Level
React API, and we use it to create React elements.
-This method takes three parameters:
a. The first argument defines type of
element to create. (h1/p/div)
b. The second argument defines
LEASE AGREEMENT
properties or attributes of the element.
c. The third argument represents the
element's children, any nodes or simple text that
are inserted between the opening and closing tag.
Module Systems
==============
1. CommonJS
module.exports = {member1,member2};
const member1 = require('Library/file name');
2. ECMASCRIPT
export member1;
export default member2;
LEASE AGREEMENT
import DefaultMember , {Namedmember} from
'file'
extensions
==========
1. React Snippet
2. ESLint
3. prettier
4. code spell checker
5. gitlens
6. vscode-icons
7. Thunder Client
LEASE AGREEMENT
Browser extension
=================
json viewer
React Plugins
=============
1. React Developer Tools
2. React-sight
3. Redux DevTools
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
React.StrictMode
================
-StrictMode is a tool for highlighting potential
problems in a react application.
-It activates additional checks and warnings for its
LEASE AGREEMENT
descendants(child elements).
-Strict mode checks are run in development mode
only,they do not impact the production build.
-Strict Mode helps with the below things:
Identifying components with unsafe
lifecycles (componentWillMount)
Warning about legacy string ref API
usage
Warning about deprecated
findDOMNode() usage
Detecting unexpected side effects
Detecting legacy context API
-ex: import React, { StrictMode } from "react";
<StrictMode>
<App />
</StrictMode>
Note: StrictMode renders components twice (on
dev but not production) in order to
detect any problems with our code and warn us
about them.
Component
=========
-Components are the most basic UI building block
LEASE AGREEMENT
of a React application.
-Each Component is responsible for outputting a
small,reusable piece of HTML.
-A Component Represents a part of the User
Interface.
-Components are Re-Usable and can be nested
inside other component.
-A React application contains a tree of components.
-React components let you split the UI into
independent, reusable pieces,
and think about each piece in isolation.
2 types Of Component
====================
1. Functional Component (
stateless/presentational/dumb)
2. Class Component ( statefull)
Functional Component
Class Component
---------------------
---------------
1. No 'this' keyword
1. More feature rich
2. solution without state
2. Maintain own private data- state
3. Mainly for UI
3. Complex UI Logic
4. Stateless/dumb/Presentational 4. Provide Life
cycle hooks
Fragments
==========
-While returning elements in JSX, we can only
return 1 element at a time.
That element can have children but we have to
ensure that we are only returning 1 element at a
time, or else we will get a syntax error. (ex: a
LEASE AGREEMENT
function can return 1 value)
-Fragments are way to render multiple elements
without using a wrapper element.
-Fragment acts as a wrapper without adding
unnecessary divs to the DOM.
-We can use it directly from the React import, or
deconstruct it.
import React from 'react';
<React.Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</React.Fragment>
-// Deconstructed
import { Fragment } from 'react';
<Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</Fragment>
-React version 16.2 simplified this process further,
allowing for empty JSX tags to be interpreted as
Fragments
<>
<div>I am an element!</div>
<button>I am another
element</button>
</>
LEASE AGREEMENT
Data Binding
============
-Binding/Displaying the variable value in UI is
called data binding.
CSS in React
============
different ways to add CSS:
1. inline CSS
2. External CSS
3. global css(index.css)
4. CSS Modules
5. Conditional CSS
CSS Modules
===========
-This approach is designed to fix the problem of the
global scope in CSS.
-A CSS Module is a CSS file in which all class names
are scoped locally by default.
-CSS Modules allow to use the same CSS class name
LEASE AGREEMENT
in different files without worrying about naming
clashes.
-CSS Modules allow the scoping of CSS by
automatically creating a unique classname of the
below format.
ex: [filename]\_[classname]\_\_[hash]
-ClassNames are dynamically generated, unique,
and mapped to the correct styles.
-When importing the CSS Module from a JS
Module, it exports an object.
import styles from './Button.module.css';
// Import css modules stylesheet as styles
import './another-stylesheet.css'; //
Import regular stylesheet
<button className={styles.error}>Error
Button</button>;
-it will only apply the classname from css module
even if both files have same 'error' class;
Conditional Rendering
=====================
-It is a common use case to show or hide elements
based on certain conditions.
LEASE AGREEMENT
-it allows us to render different elements or
components based on a condition.
-use cases:
Rendering external data from an API.
Showing or hiding elements.
Toggling application functionality.
Implementing permission levels.
Handling authentication and
authorization.
-ways to implement conditional rendering:
Using an if…else Statement
Using a switch Statement
Using Ternary Operators
Using Logical && (Short Circuit
Evaluation)
Ternary- <div>{flag ?
<h1>Helllloooooo</h1> : null}</div>
Short Circuit- <div>{flag &&
<h1>Helllloooooo</h1>}</div>
Assignment
==========
1. create products.json with list of products.
https://fakestoreapi.com/products
2. display the products in table & card
forceUpdate
===========
LEASE AGREEMENT
-Declaring class variables/function variables is
always a bad idea.
-can be used for the below 2 use cases:
Setting and clearing timeouts
Storing frequently-referenced values
props
=====
-Props are inputs to components.
-Props stand for properties and is a special keyword
in React.
LEASE AGREEMENT
-Attributes on Components get converted into an
object called Props.
-Helps to Pass custom data to a component.
-props are used to pass data and methods from a
parent component to a child component.
-data with props are being passed in a
uni-directional flow. (one way from parent to child).
-We can pass props to any component as we declare
attributes for any HTML tag
<ChildComponent someAttribute={value}
anotherAttribute={value}/>
-React props passed with just their name have a
value of true.
<myComponent showTitle={true}>
<myComponent showTitle>
-The props can be accessed as shown below
this.props.propName; (Class Component)
props.propName; (Functional Component)
Props De-structuring
====================
-It’s a JavaScript feature that allows us to extract
multiple pieces of data from an array or object and
assign them to their own variables.
-Improves readability.
-we can get rid of props/this.props in front of each
property.
PropTypes
=========
-React has some built-in typechecking abilities.
-To run typechecking on the props for a
component,we can assign the special propTypes
property.
-PropTypes exports a range of validators that can
be used to make sure the data the component
LEASE AGREEMENT
receive is valid.
-When an invalid value is provided for a prop, a
warning will be shown in the browser console.
-For performance reasons, propTypes is only
checked in development mode.not in production.
};
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
optionalElement: PropTypes.element,
optionalEnum: PropTypes.oneOf(['News',
'Photos']),
optionalArrayOf:
PropTypes.arrayOf(PropTypes.number),
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
LEASE AGREEMENT
fontSize: PropTypes.number
}),
Requiring Props
===============
-If prop values are not passed to a certain
component, no error will be thrown.
Instead, within the component that prop will have a
value of 'undefined'.
-Apart from specifying the type of the prop that can
be passed to the component,
we can also make sure the prop is always provided
to the component by chaining
isRequired at the end of the prop validator.
Student.propTypes = {
name: PropTypes.string.isRequired, // Required
Prop
age: PropTypes.number // Optional Prop
}
Default props
LEASE AGREEMENT
=============
-defaultProps allows to set default value for props.
-ex:
Greet.defaultProps = {
msg: 'this is my default
message'
}
-Functional Component & destructuring
export default function Greet({name , msg='good
morning'}) {
}
Props.children
==============
-props.children represents the content between the
tags of a Component.
-props.children can be an array or a single item.
-props.children is available on every component.
-<Welcome>Hello world!</Welcome>
-The string Hello world! is available in
props.children in the Welcome component.
-class Welcome extends React.Component {
render() {
return <p>{this.props.children}</p>;
}
LEASE AGREEMENT
}
Prop Drilling
=============
-Prop drilling is the process in a React app where
props are passed from one component to another
by going through other parts that do not need the
data, but only help in passing it through the
intermediate components.
-The problem with this approach is that most of the
components through which this data is passed have
LEASE AGREEMENT
no actual need for this data.
-They are simply used as mediums for transporting
this data to its destination component.
-as the components are forced to take in unrelated
data and pass it to the next component, which in
turn passes it, and so on, until it reaches its
destination.
This can cause major issues with component
reusability and app performance.
-This Problem Can be avoided by using concepts
like 'Context API' & 'REDUX'
States
======
-the State of a component is an object that holds
some information
that may change over the lifetime of the
component.
-whenever the state object changes,react will
re-render the component.
render() gets re-invoked.
Note:
-----
-setState() actions are asynchronous. setState()
doesn’t immediately mutate this.state.
LEASE AGREEMENT
-React may group multiple setState() calls in to a
single update for better performance
-when we want to update the state based on the
previous State value,
we need to pass a function as an arguement to
setState() instead passing an object.
ex:- this.setState({ value: this.state.value + 1 });
this.setState(prevState => ({ value:
prevState.value + 1 }));
Props
vs
State
==================================
==================================
===
1. Props are immutable.
1. State is mutable/modifiable.
2. pass data from parent component
2. contains own data & changes over time
to child component
3. communicate between components
3. rendering dynamic changes
4. props - Functional Comp
4. useState() - Functional Comp
LEASE AGREEMENT
this.props - class comp
this.state={} - Class Comp
1. npm i sweetalert2
2. import Swal from 'sweetalert2'
3. on button click call a function, which has the
below code
Swal.fire(
'Good job!',
'You clicked the button!',
'success'
)
Search
======
1. Install react-js-search from npm
npm i react-js-search
2. Import SearchBar in your react component
import SearchBar from 'react-js-search';
3. use the below HTML
<SearchBar
onSearchTextChange={(term, filteredData) =>
{
setFilteredEmployees([...filteredData]);
}}
onSearchButtonClick={onSearchClick}
placeHolderText={"Search here..."}
data={employees}
/>
Pagination
==========
1. npm install react-paginate
2. import ReactPaginate from 'react-paginate';
3. <Employees> / <Products> / <Users>
<ReactPaginate
LEASE AGREEMENT
breakLabel="..."
nextLabel="next >"
onPageChange={handlePageClick}
pageRangeDisplayed={5}
pageCount={pageCount}
previousLabel="< previous"
renderOnZeroPageCount={null}
/>
React Events
============
-React events are written in camelCase
onClick-correct
onclick-wrong
-React event handlers are written inside curly braces
onClick={shoot} instead of
onClick="shoot()"
<button onClick={shoot}>Take the
Shot!</button> // calls the function on click
<button onClick={shoot()}>Take the
Shot!</button> // calls the function on load
-For methods in React,the 'this' keyword should
represent the component that owns the method.
-That is why we should use arrow functions.
LEASE AGREEMENT
With arrow functions, 'this' will always represent
the object that defined the arrow function.
-In class components, the this keyword is not
defined by default,
so with regular functions the this keyword
represents the object that called the method, which
can be the global window object, a HTML button, or
whatever.
-If you must use regular functions instead of arrow
functions you have to
bind 'this' to the component instance using the
bind() method.
constructor(props) {
super(props);
this.f1 = this.f1.bind(this);
}
state = {
counter: 0
}
f1() {
alert("hi");
console.log(this)
console.log(this.state.counter)
}
SyntheticEvent
==============
-SyntheticEvent is a cross-browser wrapper around
the browser’s native event.
-in React event handlers receive 'SyntheticEvent'
object as arguement insteadof browser's native
'Event' object.
Component Communication
=======================
->Parent to Child : props
->Child to Parent : callback and states
->Between Siblings : Combine the above 2
Child To Parent:
1. Define a function in parent which takes the data
as a parameter.
2. Pass that function as a prop to the child.
3. Call the function using this.props.[callback] in the
LEASE AGREEMENT
child, pass in the data as the argument.
Component vs PureComponent
==========================
-PureComponent is exactly the same as Component
except that it handles the
'shouldComponentUpdate' method for us.
-When props or state changes, PureComponent will
do a shallow comparison on both props and state.if
there is a change in state/props, then only render()
will be called.
-A normal Component always calls render() when
we update the state. even though there is no
change in the last state data and current state data.
-Class components that extend the
React.PureComponent class are treated as pure
components.
Ex: class myComp extends
React.PureComponent {
}
-in Functional components, re-render happens only
if the state changes.
-Every Functional Component is a Pure-Component.
LEASE AGREEMENT
useMemo()
========
-The functions called inside component are
re-invoked on every state change.
-If we want the functions should be called only on
page load and not on every state changes then for
that function, useMemo should be used.
-useMemo Hook returns a memoized value.
LEASE AGREEMENT
-The useMemo(()=>{} , []) hook accepts a second
parameter to declare dependencies.
The function will only run when its dependencies
are changed.
-The main difference between usememo() and
useCallBack() is that
useMemo() returns a memoized value and
useCallback() returns a memoized function.
ex:
// const calculation = expensiveCalculation(count);
// function gets called on every state change
// const calculation = useMemo(() =>
expensiveCalculation(count), []); // function gets
called on page load
const calculation = useMemo(() =>
expensiveCalculation(count), [count]); // function
gets called on count change
useCallBack()
=============
-useCallback() Hook returns a memoized callback
function.
-useCallback() Hook only runs when one of its
dependencies update.
LEASE AGREEMENT
-useCallback() should be used to prevent a
component from re-rendering unless its props have
changed.
-When a function is passed as a props from parent
to child component,child component re-renders
even if no props data changes(even though the
child is a memo component)
-the function that gets passed as a props gets a new
reference everytime there is a state change in
parent component.
ex:
<ToDoDemo todos={todos} addTodo={addTodo}
/>
LifeCycle Hooks
LEASE AGREEMENT
===============
-Every component in React goes through a lifecycle
of events.
-The three phases are:
1.Mounting -
(constructor,getDerivedStateFromProps,render,com
ponentDidMount)
2.Updating -
(getDerivedStateFromProps,shouldComponentUpda
te,render,
getSnapshotBeforeUpdate, componentDidUpdate)
3.Unmounting -
(componentWillUnmount)
constructor()
-----------
-The constructor() method is called before anything
else, when the component is initiated.
-It is the natural place to set up the initial state and
other initial values.
-The constructor() method is called with the props,
as argument,
and you should always start by calling the
'super(props)' before anything else,
Otherwise,this.props will be undefined.
-This will initiate the parent's constructor method
and allows the component to inherit methods from
its parent (React.Component).
-If you neither initialize state nor bind methods for
your React component, there is no need to
implement a constructor for React component.
-setState() method should not be called in the
constructor(). we will get console error
error - Can't call setState on a component that is
not yet mounted
static getDerivedStateFromProps()
--------------------------------
-The getDerivedStateFromProps() method is called
LEASE AGREEMENT
right before rendering the element(s) in the DOM.
-This is the natural place to set the state object
based on the initial props.
-It takes (props,state) as argument, and returns an
object with changes to the state.
-only fires when the parent causes a re-render and
not as a result of a local setState.
render()
-------
-The render() method is required, and is the method
that actual outputs HTML to the DOM.
-it gets re-invoked when state/props data changes.
componentDidMount()
------------------
-The componentDidMount() method is called after
the component is rendered.
-This is a good place to initiate the network request.
-if we are going to fetch any data from an API then
API call should be placed in this lifecycle
method,and then we get the response, we can call
the setState() method and render the element with
updated data.
LEASE AGREEMENT
-good place for DOM manipulation.
Updating
=========
1.static getDerivedStateFromProps(props,state)
2.shouldComponentUpdate()
3.render()
4.getSnapshotBeforeUpdate(prevProps, prevState)
5.componentDidUpdate()
getDerivedStateFromProps()
-----------------------
-while updating state/props
getDerivedStateFromProps() method is called.
-This is the first method that is called when a
component gets updated.
-This is still the natural place to set the state object
based on the initial props.
shouldComponentUpdate()
----------------------
-In the shouldComponentUpdate() method a
boolean value should be returned that specifies
LEASE AGREEMENT
whether React should continue with the rendering
or not.
-The default value is true.
-shouldComponentUpdate() lifecycle shouldn't be
added if the class is extending
React.PureComponent.
getSnapshotBeforeUpdate(prevProps, prevState)
------------------------
-In the getSnapshotBeforeUpdate(prevProps,
prevState) method we have access to the props and
state before the update,meaning that even after the
update, we can check what the values were before
the update.
example:
-When the component is mounting it is rendered
with the favorite color "red".
-When the component has been mounted, a timer
changes the state, and after one second,the favorite
color becomes "yellow".
-This action triggers the update phase, and since
this component has a getSnapshotBeforeUpdate()
method,this method is executed, and writes a
message to the empty DIV1 element.
LEASE AGREEMENT
componentDidUpdate()
-------------------
-The componentDidUpdate() method is called after
the component is updated in the DOM.
-componentDidUpdate() is invoked immediately
after the state is updated.
-This method is not called for the initial
render,componentDidMount() will be called for the
initial render.
-it gets called only when state/props gets updated.
componentWillUnmount()
---------------------
-Called immediately before a component is
LEASE AGREEMENT
destroyed.
-Perform any necessary cleanup in this method,
such as cancel network requests,
or cleaning up any DOM elements created in
componentDidMount.
-clearTimeout, ClearInterval , Unsubscribe,
detachEventHandlers
useEffect()
----------
-useEffect serves the same purpose as
componentDidMount, componentDidUpdate, and
componentWillUnmount.
-useEffect() takes a callBack Function as 1st
argument and an arrray as 2nd argument.
ex: useEffect(()=>{} , []);
-array contains dependencies for useEffect, that is,
variables on which useEffect depends on to re-run.
-If 2nd argument is not present, effect runs
everytime there is a state change.
-When the array is empty, the effect runs only
once.(on component load)
-If 2nd arguement is present, effect will only run if
the values in the list change.
-we can have many useEffects() in a component to
LEASE AGREEMENT
track changes for diff variables.
useLayoutEffect
===============
LEASE AGREEMENT
-useLayoutEffect is a version of useEffect that fires
before the browser repaints the screen.
-This runs synchronously immediately after React
has performed all DOM mutations.
-useLayoutEffect(callBack, dependencies?)
-useLayoutEffect: If you need to mutate the DOM
inside the effect()
Forms
=====
-React uses forms to allow users to interact with the
web page.(Collect User Data)
-get the field value by using the
'event.target.value',
get the field name by using 'event.target.name'
-control the submit action by adding an event
handler in the onSubmit attribute.
-Add a submit button and an event handler with
LEASE AGREEMENT
onSubmit attribute.
<form onSubmit={this.submitHandler}>
<button>submit</button>
</form>
-use event.preventDefault() to prevent the form
from actually being submitted.(to avoid page
refresh)
-control the values of more than one input field by
adding a name attribute to each element.
<select>
<option value="Ford">Ford</option>
<option value="Volvo"
selected>Volvo</option>
<option value="Fiat">Fiat</option>
</select> //wrong
Feature
Uncontrolled
Controlled
------------------------------------------------------------
-----------
One-time value retrieval
(e.g. on submit)
yes
yes
Validating on submit
yes
yes
LEASE AGREEMENT
Default Value
yes yes
Field-level Validation
no
yes
Conditionally disabling submit button
no
yes
Enforcing input format
no
yes
dynamic inputs
no
yes
PUT vs POST
-----------
-POST for CREATE operation, PUT is for create &
update.
-PUT is idempotent, where POST is
LEASE AGREEMENT
non-idempotent.
-Idempotence(producing the same result even if the
same request is made multiple times)
-(PUT)if you retry a request N times, that should be
equivalent to single request modification.
-(POST)if you retry the request N times, you will
end up having N resources with N different URIs
created on server
-Use PUT when you want to modify a singular
resource which is already a part of resources
collection.
-Use POST when you want to add a child resource
under resources collection.
PUT vs PATCH
------------
-PUT is used to replace an existing resource.
-PATCH is used to apply partial modifications to a
resource.
POSTMAN
=======
-Application, used to Test REST APIs.
(chrome://apps/)
-Send requests, get responses, and easily debug
REST APIs.
-Browser Extension / Application
https://www.postman.com/downloads/
-Thunder Client(VSCode Extension) is an alternate
to postman
http://localhost:3000/employees
GET /employees
GET /employees/{id}
POST /employees
PUT /employees/{id}
PATCH /employees/{id}
DELETE /employees/{id}
Async Await
===========
const fetchProducts = async function () {
const products = await
fetch("https://fakestoreapi.com/products");
const productsJSON = await products.json();
setProducts(productsJSON);
};
Axios
fetch()
==================================
==================================
=======
-built-in XSRF protection.
-Fetch does not.
-uses the data property.
-Fetch uses the body property.
-data contains the object.
-Fetch’s body has to be
stringified.
-request is ok when status is 200 and statusText is
‘OK’. Fetch request is ok when response object
contains the ok property.
-performs automatic transforms of JSON data.
Fetch is a two-step process when handling JSON
data- first, to make the actual request; second, to
call the .json() method on the response.
LEASE AGREEMENT
-allows cancelling request and request timeout.
Fetch does not.
-has the ability to intercept HTTP requests.
Fetch, by default, doesn’t
-has built-in support for download progress.
Fetch does not support upload progress.
Http Interceptors
=================
-Interceptor is a feature that allows an application
to intercept/modify requests or responses before
they are handled by .then() or the .catch()
url-->response-->interceptor-->modifiedResponse-
->component
axios.interceptors.response.use(
res => res,
err => {
if (err.response.status === 404) {
throw new Error(`${err.config.url} not found`);
}
throw err;
}
);
remove an interceptor
---------------------
const myInterceptor =
axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
use cases:
-Infinite scroll in three different views, all having
different data.
-Components using data from third party
subscription.
-Components that need logged in user data.
-Showing multiple lists(e.g. Users, Locations) with
search feature.
https://www.codingame.com/playgrounds/8595/re
actjs-higher-order-components-tutorial
LEASE AGREEMENT
Routing
=======
-Single Page Applications(SPAs) are web
applications that load a single HTML page and
dynamically update that page as user interacts with
the application.
-Complete page Re-load doesn't happen. only a
portion of a page gets loaded.
-Routing in a Single Page Application is the way to
introduce some features for navigating the
application through links.
-Every time a link is clicked or browser URL changes,
React Router makes sure
our application loads component accordingly.
-The browser should change the URL when you
navigate to a different screen.
-The browser back and forward button should work
as expected.
-Routing links together your application navigation
with the navigation features offered by the
browser: the address bar and the navigation
buttons.
LEASE AGREEMENT
-React Router offers a way to write your code so
that it will show certain components of your app
only if the route matches what you define.
Types of routes:
================
React Router provides two different kind of routes:
1. BrowserRouter (builds classic URLs)
2. HashRouter (builds URLs with the hash)
https://application.com/dashboard //
BrowserRouter ( IE>9 (OR) any other browser )
https://application.com/#/dashboard //
HashRouter (IE<9)
<BrowserRouter>
<App />
</BrowserRouter>
4. add the <Routes> element (ensures that only one
component is rendered at a time)
and add <Route> to create the link between
LEASE AGREEMENT
components
<Routes>
<Route exact path="/" element={<Home />}
/>
<Route exact path="/home" element={<Home
/>} />
<Route exact path="/aboutus"
element={<AboutUs />} />
<Route exact path="/products"
element={<Products />} />
<Route path="*" element={<NotFound />} />
(No Match Route)
</Routes>
5. Add a Link for each component and use
to="URL" to link them.
<div>
<Link to="/">Home </Link>
<Link to="/about">About Us </Link>
<Link to="/shop">Shop Now </Link>
</div>
Link vs NavLink
===============
-When we use <Link> there isn't any active class on
selected element.
LEASE AGREEMENT
-with <NavLink> the selected element is
highlighted because this element adds an active
class.
-add below css:
nav
a.active{text-decoration:none;font-weight:bolder;ba
ckground-color: aqua}
Navigating Programatically
==========================
import React from "react";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
export default function AboutUs() {
const navigate = useNavigate();
const func1 = function () {
alert("do something");// logic
navigate('/products');
LEASE AGREEMENT
};
return (
<>
<h1>this is about us component</h1>
<Link to="/products">Take me to products
page</Link>
<button onClick={func1}>Take me To
product</button>
</>
);
}
Route Params
============
1. Path params (productdetails/101)
2. Query Params (search?name=sachin&age=25)
Path Params
-----------
1. configure the route
<Route path="/productdetails/:id"
element={<ProductDetails />} />
2. create a link to that route (ProductList - for Every
Product)
<Link to={`/productdetails/${id}`}> View
Details</Link>
3. collect the params data and display
const { id } = useParams();
<h1>This is the details of product - {id}</h1>
Query params
------------
1. configure the route
<Route path="/productdetails"
LEASE AGREEMENT
element={<ProductDetails />} />
2. create a link & navigation logic
const navigate = useNavigate();
const navigateHandler = (title, price) => {
navigate({
pathname: "/productdetails",
search: `?${createSearchParams({ title, price })}`,
});
};
<button className="btn btn-secondary"
onClick={() => {
navigateHandler(title, price);
}}>query param</button>
Index Route
===========
LEASE AGREEMENT
-A child route with no path that renders in the
parent's outlet at the parent's URL.
-Child Path would remain same like parent route.
<Route path="/products"
element={<Products />}>
<Route index
element={<FeaturedProducts />} />
<Route path="featured"
element={<FeaturedProducts />} />
<Route path="new"
element={<NewProducts/>}/>
</Route>
<Outlet />
Protected Routes
================
-Protected Routes are routes that can only be
accessed if a condition is met(usually, if user is
properly authenticated).
-It returns a Route that either renders a component
or redirects a user to another route based on a set
condition.
Replace
=======
-replaces the current location instead of pushing a
new one onto the browser history stack
<Navigate to="/home" replace />
(OR)
navigate("/home", { replace: true })
Exact
=====
-The exact param disables the partial matching for a
route and makes sure that it only returns the route
if the path is an EXACT match to the current url.
}
-To handle errors in event handlers.
-To handle errors in server-side rendering.
Error Boundaries
================
-A JavaScript error in a part of the UI shouldn’t
break the whole app.
To solve this problem, React 16 introduced a new
concept “error boundary”
-Error boundaries are React components that catch
JavaScript errors anywhere in their child component
tree, log those errors, and display a fallback UI
instead of the component tree that crashed.
LEASE AGREEMENT
-Error boundaries do not catch errors for below
things:
Event handlers
Asynchronous code (e.g. setTimeout or
requestAnimationFrame callbacks)
Server side rendering
Errors thrown in the error boundary itself
(rather than its children)
-A class component becomes an error boundary if it
defines componentDidCatch().
-Error boundaries work like a JavaScript catch {}
block, but for components.
-Error boundaries only catch errors in the
components below them in the tree.
An error boundary can’t catch an error within itself.
-We can use static getDerivedStateFromError() to
render a fallback UI when an error has been thrown,
and can use componentDidCatch() to log error
information.
React Profiler
==============
-Profiler measures how often a React application
renders and what the “cost” of rendering is.
LEASE AGREEMENT
-A Profiler can be added anywhere in a React tree to
measure the cost of rendering that part of the tree.
-It requires two props: an id (string) and an
onRender callback (function)
-For example, to profile a Navigation component
and its descendants:
<Profiler id="Navigation"
onRender={callbackToProcessRenderInfo}>
<Navigation {...props} />
</Profiler>
function callbackToProcessRenderInfo(id, phase,
actualDuration, baseDuration, startTime,
commitTime) {
// we can log it to a database or render it out as a
chart
logToDatabase({ id, phase, actualDuration,
baseDuration, startTime, commitTime })
}
-Profiling adds some additional overhead, so it is
disabled in the production build.
-Although Profiler is a light-weight component, it
should be used only when necessary.
Pre-requisites:
---------------
-The application should have React version 16.5 or
above.
LEASE AGREEMENT
-The React DevTools Extension needs to be installed
in your browser.
<Profiler id="counterExample"
onRender={console.log}>
<StateDemo2 />
</Profiler>
React Portals
=============
-Portals provide a way to render some Content into
a DOM node that exists outside the DOM hierarchy
of the parent component.
-To insert HTML Content into a different
location(not in the parent) in the DOM.
-createPortal() allows to render some children into a
different part of the DOM.
createPortal(children, domNode, key?)
https://cra.link/deployment
Generated Files:
main.[hash].js - This is our
application code
[number].[hash].chunk.js - vendor code
runtime-main.[hash].js - webpack
runtime logic which is used to load and run your
application
WebPack
-------
-Webpack is an open-source JavaScript module
bundler.
-It is made primarily for JavaScript, but it can
transform front-end assets like
HTML, CSS, and images if the corresponding
loaders are included.
-webpack takes modules with dependencies and
generates static assets
representing those modules.
package.json vs package-lock.json
=================================
-Package.json is mandatory
-package-lock.json is Optional (can be generated by
running 'npm i')
Dependencies VS Dev-Dependencies
================================
- if we need any libraries only at the time of
development but not in production, those libraries
LEASE AGREEMENT
should be added to DevDependencies.
(karma,jasmine,tslint,eslint,cli,jest)
ex: npm i --save-dev eslint
Available Scripts
=================
-package.json has a list of scripts
-npm start : Runs the app in the development
mode.
Open
http://localhost:3000 to view it in the browser.
The page will reload
if you make changes in files.
-npm test : Launches the test runner in the
interactive watch mode.
See the section about
running tests for more information.
-npm run build: Builds the app for production to
the build folder.
LEASE AGREEMENT
It correctly
bundles React in production mode and optimizes
the build
for the best performance.
-npm run eject: If you aren’t satisfied with the build
tool and configuration choices,
you can
eject at any time. This command will remove the
single build
ESLint
======
-ESLint is a static code analysis tool for identifying
problematic patterns found in JavaScript code.
1. npm i eslint -g
2. npm init @eslint/config
(OR)
npx eslint --init
3. eslint .
LEASE AGREEMENT
Environment Variables
=====================
-Environment variables allow to define values on a
system-wide level.
-Avoid the hassle of where to put them in code.
-It keeps sensitive data separated from code.
-There is a built-in environment variable called
NODE_ENV,we can read it from
process.env.NODE_ENV
npm start NODE_ENV development
npm test NODE_ENV test
npm run build NODE_ENV production
-follow the below steps to create custom
environment variables
1. create .env file in project
2. Add variables in that file
Note:create custom environment variables
beginning with REACT_APP_
3. use environemnt variable in any component
console.log(process.env.REACT_APP_MY_NAME);
<h1>Your name is:
{process.env.REACT_APP_MY_NAME}</h1>
https://create-react-app.dev/docs/adding-custom-e
nvironment-variables/
LEASE AGREEMENT
Context API
===========
-React context API helps to avoid the problem of
props drilling.
-Context provides a way to pass data through the
component tree without passing
props through intermediate components.
-Context is primarily used when some data needs to
be accessible by many
components at different nesting levels.
-Context is designed to share data that can be
considered “global” for a tree
of React components.
-useful and ideal for small applications where state
changes are minimal.
-ex: current authenticated user, theme, or preferred
language.
Redux
=====
-Redux is a state management library.
-Redux stores the state of our application.
-With Redux the state is maintained outside the
React component,not in a particular component.
-Redux 1.0 August 2015
-React-Redux is the library that provides binding to
use React and Redux together in an application.
-In a typical Redux app there will be a single store &
Root-reducer.
-As Your app grows, you split the Root Reducer in
LEASE AGREEMENT
to smaller reducers
independently operating on the different parts of
the state tree.
3 Principles
===========
1. The state of our whole application is stored in an
object tree within a single store.
Maintain your whole application state in a single
LEASE AGREEMENT
object which would be managed by the Redux
store.
Store
======
-One store for the entire application.
-Holds applications state.
-Allows access to state via getState()
-Allows state to be updated via dispatch(action)
-Register Listeners via subscribe(listner)
-Handles unregistering of listners via the function
returned by subscribe(listner).
LEASE AGREEMENT
Actions
=======
-The only way your application can interact with the
store.
-carry some information from your React
application to the Redux store.
-plain javascript objects.
-Have a 'type' property that indicates the type of
action being performed.
-The type of property is typically defined as a string
constants.
Reducers
=========
-Specify how the application state changes in
response to actions sent to the store.
-Function that accepts state and actions as
arguement, and returns the next state of the
application.
-reducer1(previous state, action)=>newState
-Instead of mutating the state directly,we specify
the mutations you want to
happen with plain objects called actions.
-Then we write a special function called a Reducer
to decide how every action transforms the entire
LEASE AGREEMENT
applications state.
Redux Toolkit
=============
1.Create a new project
npx create-react-app employee-mgmt --template
redux
2.Install Redux Toolkit and React Redux (for
existing react app)
npm install @reduxjs/toolkit react-redux
3.Create a Redux store with configureStore
configureStore() accepts a reducer
function as a named argument
configureStore() automatically sets up the
store with good default settings
4.Provide the Redux store to the React application
components
Put a React-Redux <Provider>
LEASE AGREEMENT
component around your <App />
Pass the Redux store as <Provider
store={store}>
5.Create a Redux "slice" reducer with createSlice
Call createSlice with a string name, an
initial state, and named reducer functions
Reducer functions may "mutate" the state
using Immer
Export the generated slice reducer and
action creators
6.Use the React-Redux useSelector/useDispatch
hooks in React components
Read data from the store with the
useSelector hook
Get the dispatch function with the
useDispatch hook, and dispatch actions as needed
REDUX Middlewares
=================
-basic Redux store enables to perform synchronous
updates only.
Middleware Redux extends the store’s capabilities.
Redux middleware acts as a medium to interact
with dispatched actions before they reach the
LEASE AGREEMENT
reducer.
-Middleware helps with logging, error reporting,
making asynchronous requests.
Thunks
======
-Thunks are the standard approach for writing
async logic in Redux apps.
-Redux thunk allows to call action creators, which
then returns a function
instead of an action object.
This function receives the store’s dispatch method,
which is then used to dispatch the regular
synchronous actions within the function’s body
once the asynchronous operations is completed.
-This feature of thunk redux also allows us dispatch
after certain conditions are met.
-Redux-Thunk allows you to dispatch special
functions, called thunks.
-a thunk is a function that (optionally) takes some
parameters and returns another function.
The inner function takes a dispatch function and a
getState function -- both of which will be supplied
LEASE AGREEMENT
by the Redux-Thunk middleware.
Thunks vs Sagas
===============
-Redux-thunk and Redux-saga are both middleware
libraries for Redux.
-Redux-Saga in comparison to Redux-Thunk is that
you can more easily test your asynchronous data
flow.
-Redux-Saga allows to express complex application
logic as pure functions called sagas.
-Pure functions are desirable from a testing
standpoint because they are predictable and
repeatable, which makes them relatively easy to
test.
-Sagas are implemented through special functions
called generator functions.
React Hooks
===========
LEASE AGREEMENT
-A Hook is a special function that lets you “hook
into” React features.
ex: useState is a Hook that lets you add React state
to function components.
-Hooks are a new addition in React 16.8
-React Hooks allow to use state , lifecycle features
and other features without writing a class.
-React has built-in hooks
useState(), useEffect(), useRef(),
useContext(), useReducer(),
useCallBack(), useMemo(),
useId(),useDebugValue(),useDeferredValue()
-we can also create our own Hooks to reuse stateful
behavior between different components.
Rules of Hooks
==============
-Only call Hooks at the top level.
Don’t call Hooks inside loops, conditions, or nested
functions.
-Only call Hooks from React function components.
Don’t call Hooks from regular JavaScript functions.
-React built-in Hooks can be called from custom
hooks.
LEASE AGREEMENT
useState
--------
ex: const [count, setCount] = useState(0);
-useState is used to declare a state variable.
-The only argument to the useState() Hook is the
initial state.
-It returns a pair of values:
a. the current state
b. a function that updates it.
useEffect
---------
-useEffect serves the same purpose as
componentDidMount, componentDidUpdate, and
componentWillUnmount.
-pass a callBack Function as 1st arguement & an
LEASE AGREEMENT
empty array as a second argument to useEffect().
-array contains so called dependencies for
useEffect, that is, variables on which useEffect
depends on to re-run.
-When the array is empty, the effect runs only once.
-If 2nd arguement is present, effect will only
activate if the values in the list change.
-you cannot return a Promise from useEffect.
useReducer
----------
-useReducer is a hook,convenient for dealing with
more complex state changes in React components.
-useReducer borrows some theory from Redux,the
concepts of reducers, action, and dispatch.
-useReducer Hook accepts two arguments.
useReducer(<reducer>, <initialState>)
-The useReducer Hook returns the current state and
a dispatch method.
const [todos, dispatch] = useReducer(reducer,
initialTodos);
Redux:
-----
LEASE AGREEMENT
-centralised state (Application State)
-adds more de-coupling
-has middlewares: Thunk , sagas , logger
-actions can only hit one Store
-more suitable for big projects
useReducer:
----------
-local state (Component State)
-comes with other native hooks
-no extra dependencies needed
-multiple stores maybe(reducers that can act as
store)
-more suitable for small projects
useId()
-------
-useId() is a hook for generating unique IDs that
can be used with HTML Elements.
-useId is not for generating keys in a list. Keys
should be generated from your data.
- Ex:
<label htmlFor={id}>Do you like
React?</label>
<input id={id} type="checkbox" name="react"/>
-For multiple IDs in the same component, append a
LEASE AGREEMENT
suffix using the same id.
<label htmlFor={id + '-firstName'}>First
Name</label>
<input id={id + '-firstName'} type="text" />
Custom Hook
===========
-Custom Hooks are reusable functions.
-When you have component logic that needs to be
used by multiple components,
we can extract that logic to a custom Hook.
-A custom Hook is a JavaScript function whose
name starts with ”use” and that
may call other Hooks.
-Helps to Avoid repetitive and redundant stateful
logic inside multiple components.
-Custom Hooks offer the flexibility of sharing logic.
-Each call to a Custom Hook gets isolated state.
LEASE AGREEMENT
Server Side Rendering
=====================
-Initially, everything was processed on the server
and an HTML page was
delivered to the client-side browser to display a
web page.
-This worked great until more interactive content
started being displayed on the web pages
-Every time some new interactivity had to be
handled, the whole page was re-compiled by the
server
-With more complex websites being made,
server-side rendering (SSR) became slow and
inefficient
1.
https://github.com/sudheerj/reactjs-interview-ques
tions
2.
https://www.freakyjolly.com/reactjs-create-todo-ap
plication-in-reactjs-using-class-components/
3. https://github.com/Asabeneh/30-Days-Of-React
4. shimmer UI
https://www.pragimtech.com/blog/reactjs/profiler-
in-react/