Mern Stack Notes
Mern Stack Notes
1) React Component:
A React component represents a small chunk of user interface in a webpage. The primary job
of a React component is to render its user interface and update it whenever its internal state is
changed. In addition to rendering the UI, it manages the events belongs to its user interface.
React component provides below functionalities.
Functional Components
In React, function components are a way to write components that only contain a render
method and don't have their own state. They are simply JavaScript functions that may or may
not receive data as parameters. We can create a function that takes props(properties) as input
and returns what should be rendered. A valid functional component can be shown in the
below example.
function WelcomeMessage(props) {
return <h1>Welcome to the , {props.name}</h1>;
}
The functional component is also known as a stateless component because they do not hold
or manage state.
Class Components
Class components are more complex than functional components. It requires you to extend
from React. Component and create a render function which returns a React element. You can
pass data from one class to other class components. You can create a class by defining a class
that extends Component and has a render function. Valid class component is shown in the
below example.
The class component is also known as a stateful component because they can hold or manage
local state.
Example
render() {
function Car() {
}
2) REACT HOOKS
Hooks allows you to use state and other React features without writing a class. Hooks are the
functions which "hook into" React state and lifecycle features from function components. It
does not work inside classes.
Hooks are backward-compatible, which means it does not contain any breaking changes.
Also, it does not replace your knowledge of React concepts.
Hooks Types
1. Basic Hooks
useState
useEffect
useContext
2. Additional Hooks
useReducer
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
3. Custom Hooks
When you have component logic that needs to be used by multiple components, we can
extract that logic to a custom Hook.
useState
It is the most common hook in react which creates the state variable in a functional
component.
const [state, setState] = useState(initialState);
To use it you can pass any value or function as an initial state and it returns an array of two
entities, the first element is the initial state and the second one is a function (dispatcher) which
function FavoriteColor() {
useEffect
useEffect is the second most used hook in React. It just called the passed function just after the
function Timer() {
useEffect(() => {
setTimeout(() => {
}, 1000);
});
root.render(<Timer />);
useContext
It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone.
function Component1() {
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</UserContext.Provider>
);
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
}
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
</>
);
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
function Component5() {
return (
<>
<h1>Component 5</h1>
);
root.render(<Component1 />);
In ReactJS, every component creation process involves various lifecycle methods. These
lifecycle methods are termed as component's lifecycle. These lifecycle methods are not very
complicated and called at various points during a component's life. The lifecycle of the
component is divided into four phases. They are:
1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase
1. constructor()
The constructor() is the very first method called as the component is “brought to life.”
The constructor method is called before the component is mounted to the DOM. In most
cases, you would initialize state and bind event handlers methods within the constructor
method.
2. static getDerivedStateFromProps()
static getDerivedStateFromProps is a new React lifecycle method as of React 17 designed to
replace componentWillReceiveProps.
Its main function is to ensure that the state and props are in sync for when it’s required.
static getDerivedStateFromProps() {
//do stuff here
}
}
static getDerivedStateFromProps() takes in props and state:
...
...
...
Or you can return null to make no updates:
...
...
render()
After the static getDerivedStateFromProps method is called, the next lifecycle method in line
is the render method:
You could also return plain strings and numbers, as shown below:
This function is invoked immediately after the component is mounted to the DOM.
You would use the componentDidMount lifecycle method to grab a DOM node from the
component tree immediately after it’s mounted.
For example, let’s say you have a modal and want to render the content of the modal within a
specific DOM element:
el = document.createElement("section");
componentDidMount() {
document.querySelector("body).appendChild(this.el);
}
// using a portal, the content of the modal will be rendered in the DOM element attached to
the DOM in the componentDidMount method.
}
Updating lifecycle methods
Whenever a change is made to the state or props of a React component, the component is
rerendered. In simple terms, the component is updated. This is the updating phase of the
React component lifecycle.
static getDerivedStateFromProps()
The static getDerivedStateFromProps is the first React lifecycle method to be invoked during
the updating phase.
shouldComponentUpdate()
Oncethe static getDerivedStateFromProps method is called,
the shouldComponentUpdate method is called next. This lifecycle method is mostly used for
performance optimization measures.
render()
After the shouldComponentUpdate method is called, render is called immediately afterward,
depending on the returned value from shouldComponentUpdate, which defaults to true .
getSnapshotBeforeUpdate()
The getSnapshotBeforeUpdatelifecycle method stores the previous values of the state after
the DOM is updated. getSnapshotBeforeUpdate() is called right after the render method.
componentDidUpdate()
The componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate.
As with the getSnapshotBeforeUpdate method it receives the previous props and state as
arguments:
componentDidUpdate(prevProps, prevState) {
}
Unmounting lifecycle method
componentWillUnmount()
The componentWillUnmount lifecycle method is invoked immediately before a component is
unmounted and destroyed. This is the ideal place to perform any necessary cleanup such as
clearing up timers, cancelling network requests, or cleaning up any subscriptions that were
created in componentDidMount() as shown below:
static getDerivedStateFromError()
Whenever an error is thrown in a descendant component, this method is called first, and the
error thrown passed as an argument.
Whatever value is returned from this method is used to update the state of the component.
componentDidCatch()
The componentDidCatch method is also called after an error in a descendant component is
thrown. Apart from the error thrown, it is passed one more argument which represents more
information about the error
4) React Forms
1. Uncontrolled component
2. Controlled component
Uncontrolled component
The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself
handles the form data. Here, the HTML elements maintain their own state that will be
updated when the input value changes. To write an uncontrolled component, you need to use
a ref to get form values from the DOM. In other words, there is no need to write an event
handler for every state update. You can use a ref to access the input field value of the form
from the DOM.
Example
In this example, the code accepts a field username and company name in an uncontrolled
component.
Controlled Component
In HTML, form elements typically maintain their own state and update it according to the
user input. In the controlled component, the input form element is handled by the component
rather than the DOM. Here, the mutable state is kept in the state property and will be updated
only with setState() method.
Controlled components have functions that govern the data passing into them on
every onChange event, rather than grabbing the data only once, e.g., when you click
a submit button. This data is then saved to state and updated with setState() method. This
makes component have better control over the form elements and data.
A controlled component takes its current value through props and notifies the changes
through callbacks like an onChange event. A parent component "controls" this changes by
handling the callback and managing its own state and then passing the new values as props to
the controlled component. It is also called as a "dumb component."
Example
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
5) React State
The state object is where you store property values that belongs to the component.
When the state object changes, the component re-renders. They are also responsible for
making a component dynamic and interactive.
A state must be kept as simple as possible. It can be set by using the setState() method and
calling setState() method triggers UI updates. A state represents the component's local state
or information. It can only be accessed or modified inside the component or by the
component directly. To set an initial state before any interaction occurs, we need to use
the getInitialState() method.
Example
constructor(props) {
super(props);
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
The state object can contain as many properties.We Refer to the state object anywhere in the
component by using the this.state.propertyname syntax. To change a value in the state object,
use the this.setState() method.
When a value in the state object changes, the component will re-render, meaning that the
output will change according to the new value(s).
6) React Props
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes:
Example
Example
function Car(props) {
Once you choose the path, the next step is to double-click the instal.msi binary files to
initiate the installation process. Furthermore, you will be asked for permission to run the
application.
Once you have accepted the terms and conditions, the next step is to specify the path
where you want to install node.js. Your file location is the path where you must install the
node.js in your system.
On proceeding with the Next option, the custom page setup will open up on the screen.
Here you will get four icons as stated below:
node.js runtime
NPM package manager
Online documentation shortcuts
Add to PATH
Step-6 Initiate the installation
After all these steps, you will see an install button to process the installation of node.js on
Windows. Click on the install button to initiate the installation of node.js on your
Windows.
node -v
Example:
ES6 version of TypeScript provides an arrow function which is the shorthand syntax for
defining the anonymous function, i.e., for function expressions. It omits the function
keyword. We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is
also called a Lambda function. The arrow function has lexical scoping of "this" keyword.
Syntax
If we use the fat arrow (=>) notation, there is no need to use the function keyword.
Parameters are passed in the brackets (), and the function expression is enclosed within the
curly brackets {}.
In the above example, the sum is an arrow function, "a: number, b: number" is a parameter
type, ": number" is the return type, the arrow notation => separates the function parameter
and the function body.
After compiling the above TypeScript program, the corresponding JavaScript code is:
9) DataTypes in Typescript
function
The type never is a type with no values. As a result, error(message:
you are unable to set any value to a variable that has a string): never {
Never
never type. The never type is often used to describe the throw new
return type of a function that always returns an error. Error(message);
}
Source :
(https://www.spguides.com/data-types-in-typescript-with-examples/) -example
(https://www.typescriptlang.org/docs/handbook/basic-types.html) -example
https://www.geeksforgeeks.org/data-types-in-typescript/
https://www.freecodecamp.org/news/learn-typescript-data-types-from-zero-to-hero/
From the given scenario, we can understand how conditional rendering works. Consider an
example of handling a login/logout button. The login and logout buttons will be separate
components. If a user logged in, render the logout component to display the logout button. If
a user not logged in, render the login component to display the login button. In React, this
situation is called as conditional rendering.
There is more than one way to do conditional rendering in React. They are given below.
o if
o ternary operator
o logical && operator
o switch case operator
if
It is the easiest way to have a conditional rendering in React in the render method. It is
restricted to the total block of the component. IF the condition is true, it will return the
element to be rendered. It can be understood in the below example.
1. function UserLoggin(props) {
2. return <h1>Welcome back!</h1>;
3. }
4. function GuestLoggin(props) {
5. return <h1>Please sign up.</h1>;
6. }
7. function SignUp(props) {
8. const isLoggedIn = props.isLoggedIn;
9. if (isLoggedIn) {
10. return <UserLogin />;
11. }
12. return <GuestLogin />;
13. }
14.
15. ReactDOM.render(
16. <SignUp isLoggedIn={false} />,
17. document.getElementById('root')
18. );
This operator is used for checking the condition. If the condition is true, it will return the
element right after &&, and if it is false, React will ignore and skip it.
Syntax
1. {
2. condition &&
3. // whatever written after && will be a part of output.
4. }
We can understand the behavior of this concept from the below example.
If you run the below code, you will not see the alert message because the condition is not
matching.
If you run the below code, you will see the alert message because the condition is matching.
You can see in the above output that as the condition (10 > 5) evaluates to true, the alert
message is successfully rendered on the screen.
Ternary operator
The ternary operator is used in cases where two blocks alternate given a certain condition.
This operator makes your if-else statement more concise. It takes three operands and used as
a shortcut for the if statement.
Syntax
1. condition ? true : false
If the condition is true, statement1 will be rendered. Otherwise, false will be rendered.
Example
1. render() {
2. const isLoggedIn = this.state.isLoggedIn;
3. return (
4. <div>
5. Welcome {isLoggedIn ? 'Back' : 'Please login first'}.
6. </div>
7. );
8. }
Example
1. function NotificationMsg({ text}) {
2. switch(text) {
3. case 'Hi All':
4. return <Message: text={text} />;
5. case 'Hello JavaTpoint':
6. return <Message text={text} />;
7. default:
8. return null;
9. }
10. }
In the below example, we have created a stateful component called App which maintains the
login control. Here, we create three components representing Logout, Login, and Message
component. The stateful component App will render either or depending on its current state.
Other Sources :
https://www.digitalocean.com/community/tutorials/7-ways-to-implement-conditional-
rendering-in-react-applications
https://blog.logrocket.com/react-conditional-rendering-9-methods/
https://www.w3schools.com/react/react_conditional_rendering.asp
Code splitting is a way to split up your code from a large file into smaller code bundles.
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
This is quite similar to Webpack dynamic import syntax, where the Suspense component can
be used to offer a loading state until the component is lazy loaded.
Deciding where in your app to introduce code splitting can be a bit tricky. You want to make
sure you choose places that will split bundles evenly, but won’t disrupt the user experience.
A good place to start is with routes. Most people on the web are used to page transitions
taking some amount of time to load. You also tend to be re-rendering the entire page at once
so your users are unlikely to be interacting with other elements on the page at the same time.
Here’s an example of how to setup route-based code splitting into your app using libraries
like React Router with React.lazy.
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Sources:
https://ta.reactjs.org/docs/code-splitting.html
https://www.freecodecamp.org/news/code-splitting-in-react-loadable-components/
https://www.xenonstack.com/insights/code-splitting-in-react
12) React Flux Concept
Flux is an application architecture that Facebook uses internally for building the client-side
web application with React. It is not a library nor a framework. It is neither a library nor a
framework. It is a kind of architecture that complements React as view and follows the
concept of Unidirectional Data Flow model. It is useful when the project has dynamic data,
and we need to keep the data updated in an effective manner. It reduces the runtime errors.
1. Dispatcher
2. Stores
3. Views (React components)
Flux uses a unidirectional data flow pattern to solve state management complexity.
View: this component renders the UI. Whenever any user interaction occurs on it (like an
event) then it fires off the action. Also when the Store informs the View that some change has
occurred, it re-renders itself. For example, if a user clicks the Add button.
Action: this handles all the events. These events are passed by the view component. This
layer is generally used to make API calls. Once the action is done it is dispatched using the
Dispatcher. The action can be something like add a post, delete a post, or any other user
interaction.
Dispatcher: this is the central hub and singleton registry. It dispatches the payload from
Actions to Store. Also makes sure that there are no cascading effects when an action is
dispatched to the store. It ensures that no other action happens before the data layer has
completed processing and storing operations.
Store: this holds the app state and is a data layer of this pattern. Do not consider it as a model
from MVC. An application can have one or many app stores. Stores get updated because they
have a callback that is registered using the dispatcher.
Sources: https://www.freecodecamp.org/news/how-to-use-flux-in-react-example/
https://www.javatpoint.com/react-flux-concept#:~:text=Flux%20is%20an
%20application%20architecture,of%20Unidirectional%20Data%20Flow%20model.
https://legacy.reactjs.org/blog/2014/05/06/flux.html
https://www.tutorialspoint.com/reactjs/reactjs_flux_concept.htm
Redux is an open-source JavaScript library used to manage application state. React uses
Redux for building the user interface.
o React Redux is the official UI bindings for react Application. It is kept up-to-date
with any API changes to ensure that your React components behave as expected.
o It encourages good 'React' architecture.
o It implements many performance optimizations internally, which allows to
components re-render only when it actually needs.
Redux Architecture
The components of Redux architecture are explained below.
STORE: A Store is a place where the entire state of your application lists. It manages the
status of the application and has a dispatch(action) function. It is like a brain responsible for
all moving parts in Redux.
ACTION: Action is sent or dispatched from the view which are payloads that can be read by
Reducers. It is a pure object created to store the information of the user's event. It includes
information such as type of action, time of occurrence, location of occurrence, its
coordinates, and which state it aims to change.
REDUCER: Reducer read the payloads from the actions and then updates the store via the
state accordingly. It is a pure function to return a new state from the initial state.
Redux Installation
To use React Redux with React application, you need to install the below command.
Sources : https://www.freecodecamp.org/news/how-to-use-redux-in-reactjs-with-real-life-
examples-687ab4441b85/
https://www.javatpoint.com/react-redux-example
https://www.simplilearn.com/tutorials/reactjs-tutorial/react-with-redux
Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications. React
Router is used to define multiple routes in the application. When a user types a specific URL
into the browser, and if this URL path matches any 'route' inside the router file, the user will
be redirected to that particular route.
React Router is a standard library system built on top of the React and used to create routing
in the React application using React Router Package. It provides the synchronous URL on the
browser with data that will be displayed on the web page. It maintains the standard structure
and behavior of the application and mainly used for developing single page web applications.
1. react-router: It provides the core routing components and functions for the React
Router applications.
2. react-router-native: It is used for mobile applications.
3. react-router-dom: It is used for web applications design.
It is not possible to install react-router directly in your application. To use react routing, first,
you need to install react-router-dom modules in your application. The below command is
used to install react router dom.
Example
Step-1: In our project, we will create two more components along with App.js, which is
already present.
About.js
Contact.js
App.js
Step-2: For Routing, open the index.js file and import all the three component files in it.
Here, you need to import line: import { Route, Link, BrowserRouter as Router } from
'react-router-dom' which helps us to implement the Routing. Now, our index.js file looks
like below.
What is Route?
It is used to define and render component based on the specified path. It will accept
components and render to define what should be rendered.
Index.js
Sometimes, we want to need multiple links on a single page. When we click on any of that
particular Link, it should load that page which is associated with that path
without reloading the web page. To do this, we need to import <Link> component in
the index.js file.
This component is used to create links which allow to navigate on different URLs and render
its content without reloading the webpage.
Example
Index.js
Source: https://www.javatpoint.com/react-router
https://www.geeksforgeeks.org/reactjs-router/
https://www.w3schools.com/react/react_router.asp
As we have already seen that, all of the React components have a render function. The
render function specifies the HTML output of a React component. JSX(JavaScript
Extension), is a React extension which allows writing JavaScript code that looks like HTML.
In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so
that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used
by preprocessors (i.e., transpilers like babel) to transform HTML-like syntax into standard
JavaScript objects that a JavaScript engine will parse.
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the
same file where you write JavaScript code, then preprocessor will transform these
expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name,
attributes, and children.
Example
Here, we will write JSX syntax in JSX file and see the corresponding JavaScript code which
transforms by preprocessor(babel).
1. <div>Hello JavaTpoint</div>
Corresponding Output
Uses of JSX
The concept of a constructor is the same in React. The constructor in a React component is
called before the component is mounted. When you implement the constructor for a React
component, you need to call super(props) method before any other statement. If you do not
call super(props) method, this.props will be undefined in the constructor and can lead to
bugs.
Syntax
1. Constructor(props){
2. super(props);
3. }
1. It used for initializing the local state of the component by assigning an object to
this.state.
2. It used for binding event handler methods that occur in your component.
allows developers to render their elements outside the React hierarchy tree without
comprising the parent-child relationship between components.
Usually, typical React components are located within the DOM. This means that it might be
tricky for you to render modals or pop-up windows.
Features
o It uses React version 16 and its official API for creating portals.
o It has a fallback for React version 15.
o It transports its children component into a new React portal which is appended by
default to document.body.
o It can also target user specified DOM element.
o It supports server-side rendering
o It supports returning arrays (no wrapper div's needed)
o It uses <Portal /> and <PortalWithState /> so there is no compromise between
flexibility and convenience.
o It doesn't produce any DOM mess.
o It has no dependencies, minimalistic.
o Modals
o Tooltips
o Floating menus
o Widgets
A Portal can be created using ReactDOM.createPortal(child, container). Here the child is a
React element, fragment, or a string, and the container is the DOM location(node) to which
the portal should be injected.
Even though a Portal is rendered outside of the parent DOM element, it behaves similarly to a
regular React component within the application. It can access props and the context API. This
Sources : https://betterprogramming.pub/digging-deeper-into-react-portals-with-examples-
937f925edfa4
https://legacy.reactjs.org/docs/portals.html
https://legacy.reactjs.org/docs/portals.html
https://blog.logrocket.com/learn-react-portals-example/
https://blog.bitsrc.io/understanding-react-portals-ab79827732c7
Error boundaries are React components which catch JavaScript errors anywhere in our app,
log those errors, and display a fallback UI. It does not break the whole app component tree
and only renders the fallback UI whenever an error occurred in a component. Error
boundaries catch errors during rendering in component lifecycle methods, and constructors of
the whole tree below them.
A class component becomes an error boundary if it defines either (or both) of the lifecycle
methods static getDerivedStateFromError() or componentDidCatch(). Use static
getDerivedStateFromError() to render a fallback UI after an error has been thrown.
Use componentDidCatch() to log error information.
static getDerivedStateFromError(error) { // Update state so the next render will show the
fallback UI. return { hasError: true }; }
componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting
service logErrorToMyService(error, errorInfo); }
render() {
if (this.state.hasError) { // You can render any custom fallback UI return
<h1>Something went wrong.</h1>; }
return this.props.children;
}
}