SlideShare a Scribd company logo
1 of 55
React JS
Presented By: K P Verma
React JS
React JS Features
• React is an Open Source JavaScript library used for creating dynamic and interactive
user interfaces for mobile and web applications.
• It is highly flexible, declarative, and efficient for developing scalable, simple, and fast front-
end for web and mobile applications.
• React is only concerned with rendering data to the Document Object Model (DOM) and so
creating React applications usually requires the use of additional libraries for implementing things
like state management and routing.
• DOM: Document Object Model is a way to represent the webpage in a structured hierarchical
way. With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or Elements of
HTML using commands or methods provided by the Document object. Using DOM, JavaScript gets
access to HTML as well as CSS of the web page and can also add behavior to the HTML elements.
• Virtual DOM: Virtual DOM exists which is like a lightweight copy of the actual DOM. So for every
object that exists in the original DOM, there is an object for that in React Virtual DOM. It is exactly
the same, but it does not have the power to directly change the layout of the document.
Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets drawn on the
screen.
React JS Features
• Components: The component is the most basic building block of the React Application UI.
• One-way data-binding: React JS follows one-way data binding or unidirectional data flow that
gives better control throughout the application.
• JSX: React uses JSX for building templates instead of regular JavaScript. JSX is faster than normal
JavaScript as it performs optimizations while translating to regular JavaScript.
JavaScript & HTML
JSX
• JavaScript XML: JSX is basically a syntax extension of JavaScript. It helps us to write HTML in
JavaScript and forms the basis of React Development.
• JSX creates an element in React that gets rendered in the UI. It is transformed into JavaScript
functions by the compiler at runtime.
• Error handling and warnings become easier to handle when using JSX
• Ex: const elem = <h1>This is sample JSX</h1>
Create a New Application in React
Create New App
• There are basically two methods for React JS Environment Setup
• Using create-react-app
• Using webpack and babel
• Create React using create-react-app
1. Install Node.js
2. Run: npx create-react-app app-name
3. If the command is not working run npm install create-react-app
4. New app has been created in ./app-name
5. Move to folder cd app-name
6. Run the command npm install to install all dependencies from package.json
7. Run the command npm start to view on the localhost:3000 by default.
8. When you’re ready to launch your app, run this command npm run build to prepare bundles.
9. This command will build the react app and bundle the app into CSS/JS/HTML files and put them in the
/build folder
Change listening PORT
 Update package.Json with the below code and run the application
"scripts":
{
"start": "set PORT=5000 && react-scripts start"
}
 Add a .env file in the project root and update the file with the below code.
PORT=5000
Anatomy of a new React app
Common tasks in React
Components
Components
• Components are the building blocks of any React app. These blocks are reusable and independent
like functions in JavaScript and are responsible for representing the elements on the Web Page.
• Components in React basically return a piece of JSX code that tells what should be rendered on
the screen.
• The name of a component should always start with a capital letter. This is done to differentiate a
component tag from HTML tags.
• A component is the combination of
• Template using HTML
• User Interactivity using JS
• Applying Styles using CSS
Functional Components
• It is simply a Javascript function. These functions may or may not receive data as parameters
• Use functional components only when we are sure that our component does not require
interaction or work with any other component.
Class Components
• The class components are a little more complex than the functional components.
• Class components are reusable.
• We can pass data from one class component to another class component.
• Where to use class components:
1. Managing State of the Components
2. Adding Life Cycle Methods to Components
3. Need to Write Logic for Event Handlers
Functional vs Class Components
Functional Components Class Components
It is a plain JavaScript pure function that accepts
props as an argument and returns a JSX element.
It requires to extend from React.Component
and create a render function that returns a React
element.
Functional components run from top to bottom
and once the function is returned it can’t be kept
alive.
The class component is instantiated and different
life cycle method is kept alive and is run and
invoked depending on the phase of the class
component.
Stateless components as they simply accept data
and display them in some form, they are mainly
responsible for rendering UI.
Stateful components because they implement
logic and state.
Hooks can be used in functional components to
make them Stateful.
this keyword is required, along with the
setState() function and a constructor.
A constructor is not supported by functional
components
Provide a constructor for storing state before
passing props to the parent class
Prop & state
props
• React allows to passing information to a Component using properties i.e. called props.
• Props are objects which can be used inside a component.
• The ‘this.props’ is a global object that stores all of a component’s props.
• To access a prop from a function, we no longer need to use the ‘this’ keyword. Functional
components accept props as parameters and can be accessed directly.
• Props are read-only.
• propTypes: PropTypes.string, PropTypes.bool, PropTypes.array,
PropTypes.anyOtherType
state
• React introduces, a new concept named “state” which allows React components to change their
output over time in response to user actions without violating this rule.
• State is similar to props, but it is private and fully controlled by the component.
• The state of a component is an object that contains data specific to a given component that may
change over time.
• The state is user user-defined plain javascript object.
• Props are immutable i.e. once set the props cannot be changed, while State is an observable
object that may change over time.
• States can be used in Class Components but in Functional components we have to use React
hooks(useState) to implement states.
• While Props are set by the parent component, the State is generally updated by event handlers.
Conventions to use state
• State must have some initial value that needs to define the constructor of the component’s class.
• The state should never be updated explicitly. React uses an observable object as the state that
observes what changes are made to the state and helps the component behave accordingly.
• The only time we are allowed to define the state explicitly is in the constructor to provide the
initial state.
• setState() method is the in-build method in React to update the state. setState()
method takes a single parameter and expects an object that should contain the set of values to be
updated. Once the update is done the method implicitly calls the render() method to view the
page.
• State updates should be independent. The state object of a component may contain multiple
attributes and React allows to use setState() function to update only a subset of those
attributes as well as using multiple setState() methods to update each attribute value
independently.
Prop vs state
props State
props are used to transfer data from a parent component to
a child
states are used to manage the data inside a component
itself.
Props are immutable and cannot be changed within a
component
state is mutable and can be updated using the setState
function.
Props can be used with state and functional components. The state can be used only with the state
components/class component
Props are read-only. The state is both read and write.
Props are passed down from the parent component
and are read-only within the child component
state is only accessible within the component where it is
defined.
Props can be used to customize the behavior or
appearance of a component
state is used to keep track of information that can change
over time.
Events
• React has the same events as HTML: click, change, mouseover etc.
 Adding Events
• React events are written in camelCase syntax: onClick
• React event handlers are written inside curly braces: onClick={methodname}
 Passing Arguments
• To pass an argument to an event handler, use an arrow function.
 React Event Object
• Event handlers have access to the React event that triggered the function.
Lifecycle of Components
Lifecycle of Components
• Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the
series of methods that are invoked in different stages of the component’s existence.
• React components can go through four stages of their life
• Initialization: This is the stage where the component is constructed with the given Props and default state. This is
done in the constructor of a Component Class.
• Mounting: Mounting means putting elements into the DOM or adding a new component to the screen.
• Updating: Updating is the stage when the state of a component is updated and the application is repainted.
• Unmounting: It is the final step of the component lifecycle where the component is removed from the page.
Initialization
• In this phase, the props and initial state of the component are mentioned. this is generally done in
the constructor of the component.
 constructor:
• When implementing the constructor for a React.Component subclass (parent class), we should
call super(props) before any other statement. Otherwise, this.props will be undefined in the
constructor, which can lead to bugs.
• React constructors are only used for two purposes:
• Initializing local state by assigning an object to this.state.
• Binding event handler methods.
• Super() function is to call the constructor of the parent class. It is used when we need to access a
few variables in the parent class. It returns an object which represents the parent class.
• super(props) can be called if needed to access this.props in the constructor.
• We should not call setState() in the constructor. Constructor is the only place where we should
assign this.state directly. In all other methods, we need to use this.setState() instead.
Mounting
• Mounting means putting elements into the DOM.
• The render() method is required and will always be called, the others are optional and will be
called if you define them.
• React has four in-built methods that get called, in this order, when mounting a component.
 constructor(): The constructor() method is called before anything else, when the
component is initiated, and it is the natural place to set up the initial state and other initial values.
 getDerivedStateFromProps() : The getDerivedStateFromProps() method is called right
before rendering the element(s) in both mounting and updating phase in React.
• It takes updated props and the current state as arguments and returns an object with changes to
the state.
• This is the natural place to set the state object based on the initial props.
 render(): The render() method is required and is the method that outputs the HTML to the
DOM.
 componentDidMount(): The componentDidMount() method is called after the component is
rendered.
• All the AJAX requests and the DOM or state update should be coded in this method.
Updating
• A component is updated whenever there is a change in the component's state or props.
• React has five built-in methods that get called, in this order, when a component is updated:
getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate,
componentDidUpdate
 getDerivedStateFromProps: This is the first method that is called when a component gets
updated. This method gets called just before rendering.
 shouldComponentUpdate: shouldComponentUpdate() method returns a Boolean value
that specifies whether React should continue with the rendering or not.
• Component will update if the value is true and the default value is true.
 render: The render() method is called when a component gets updated, it has to re-render the
HTML to the DOM, with the new changes.
Updating
• Render method returns one of the following types:
• React elements
• Arrays and fragments.
• Portals
• String and numbers.
• Booleans or null.
 getSnapshotBeforeUpdate: The getSnapshotBeforeUpdate() method is invoked just before the
DOM is being rendered. It is used to store the previous values of the state after the DOM is updated.
• Any value returned by getSnapshotBeforeUpdate() method will be used as a parameter for
componentDidUpdate() method.
• This function is always used along with the componentDidUpdate() method but vice-versa isn’t true.
• If the getSnapshotBeforeUpdate() method is present, you should also include the
componentDidUpdate() method, otherwise, you will get an error.
 componentDidUpdate: This method is called immediately after the component is updated in the DOM.
• The componentDidUpdate() is called after componentDidMount() and can be useful to perform some action
when the state of the component changes.
• This method can be used to execute the event when the component is visible on the DOM.
Unmounting
• When switches from one Component to another Component on the UI, the Previous component
gets removed from the DOM, and the new Component contents will be displayed in the UI.
• React has only one built-in method that gets called when a component is unmounted.
 componentWillUnmount: The componentWillUnmount() method is called when the
component is about to be removed from the DOM.
• componentWillUnmount() can be called when we want to Perform any necessary cleanup
required, such as invalidating timers, canceling network requests, or cleaning up any subscriptions
that were created in componentDidMount().
Lifecycle of Components
Routers
Router
• React Router is a standard library for routing in React. It enables the navigation among
views of various components in a React Application, allows changing the browser URL,
and keeps the UI in sync with the URL also used to track the content that the user is trying
to view.
• Create React App doesn't include page routing. To install react-router in the
application run command npm i react-router-dom in the terminal. And import
this npm to the component. This installation will add router package details in the
package.json.
 React Router Components:
• Router Type (BrowserRouter, MemoryRouter, HashRouter): It is the parent component that is used to
store all of the other components.
• Routes: It’s a new component introduced in the v6 and an upgrade of the component. The main
advantages of Routes over Switch are:
• Routes are chosen based on the best match instead of being traversed in order.
• Route: Route is the conditionally shown component that renders some UI when its path matches the
current URL.
• Link: The link component is used to create links to different routes and implements navigation around
the application. It works like an HTML anchor tag.
Types of Router
 Browser Router
• It uses HTML 5 history API (i.e. pushState, replaceState, and popState API) to keep your UI in sync
with the URL.
• It keeps the URL’s history and writes to address bar on click of browser’s back and forward button.
• It routes as a normal URL in the browser and assumes that the server is handling all the request
URLs (eg., /, /about) and points to root index.html.
 Memory Router
• It keeps the history of the URL in memory and it does not read or write to the address bar so the
user can not use the browser’s back button as well as the forward button.
• It doesn’t change the URL in your browser. It is very useful for testing and non-browser
environments like React Native.
 Hash Router
• Hash router uses client-side hash routing.
• It uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.
• The hash portion of the URL won’t be handled by the server, the server will always send the
index.html for every request and ignore the hash value.
• It doesn’t need any configuration in the server to handle routes.
React Hooks
React Hooks
• Hooks allow function components to have access to state, lifecycle methods, and other React
features. Because of this, class components are generally no longer needed.
• Hooks were added to React in version 16.8.
• Hooks provides a direct API to react concepts such as props, state, context, refs, and life-cycle.
• You must import Hooks from react.
• Hooks cannot be used with class components
• If have stateful logic that needs to be reused in several components, Custom Hooks can be built.
 Why the need for Hooks?
• Use of ‘this’ keyword
• Reusable stateful logic
• Simplifying complex scenarios
 Rules for using hooks
• Only functional components can use hooks.
• Calling of hooks should always be done at the top level of components.
• Hooks should not be inside conditional statements.
Classes vs React Hooks
Aspect Hooks Class
Syntax Hooks use regular JavaScript functions Classes use the class syntax with `extends
React.Component`.
State
Management
The useState hook is used with hooks to
define and update state variables.
In classes, the state is defined using the
`this.state` object and updated with
`this.setState()`.
Lifecycle
Methods
The `useEffect` hook in hooks is used to
handle related lifecycle events.
To handle component lifecycle events, classes contain
lifecycle methods such as
`componentDidMount`,
`componentDidUpdate`, and
`componentWillUnmount`.
Code
Organization
Hooks allow you to group together relevant logic
by breaking it into smaller custom hooks.
With classes, relevant logic and state are frequently
dispersed over many lifecycle methods and class
methods.
Reusability Hooks encourage reuse by allowing you to
design custom hooks that encapsulate a group
of related functionalities.
Classes can be reused by using higher-order components
(HOCs) or render properties.
Learning
Curve
Hooks came into use later and offer a simpler
and more logical approach to writing
React has had classes since its early versions, therefore
there are more instructional materials and code samples
Classification of React Hooks
• Hooks in React are Classified into Basic Hooks and Additional Hooks.
 Basic Hooks
• useState
• useEffect
• useContext
 Additional Hooks
• useReducer
• useCallback
• useMemo
• useRef
• useImperativeHandle
• useLayoutEffect
• useDebugValue
useState Hook
• The React useState Hook allows us to track the state in a function component. It’s similar to
this.setState in a class, except it doesn’t merge the old and new state together.
• State generally refers to data or properties that need to be tracked in an application.
• This allows one to declare a state variable inside a function.
• useState accepts an initial state and returns two values, The current state and a function that
updates the state.
• The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and
any combination of these!
• When the state of the object is updated, the entire state gets overwritten, use the JavaScript
spread operator to update a particular object item.
useEffect Hook
• The useEffect hook in React is used to handle the side effects in React such as fetching data,
updating DOM and timers.
• This hook runs on every render but there is also a way of using a dependency array using which we
can control the effect of rendering.
• The useEffect hook accepts two arguments where the second argument is optional
useEffect(<function>, <dependency>)
• This Hooks is capable of handling componentDidMount(), componentDidUpdate(), and
componentWillUnmount() life-cycle methods of class-based components into the functional
components.
• We should always include the second parameter which accepts an array. We can optionally pass
dependencies to useEffect in this array.
 Ways of controlling side effects in useEffect hook
• To run useEffect on every render do not pass any dependency
• To run useEffect only once on the first render pass any empty array in the dependency
• To run useEffect on change of a particular value. Pass the state and props in the dependency
array
Lifecycle methods using useEffect
 For componentDidMount
 For componentDidUpdate
 For componentWillUnmount
useContext
• React Context is a way to manage the state globally. Context is primarily used when some data
needs to be accessible by many components at different nesting levels.
• React Context is a method to pass props from parent to child component(s), by storing the props in
a store and using these props from the store by child component(s) without actually passing them
manually at each level of the component tree.
• It can be used with the useState Hook to share the state between deeply nested components
more easily than with useState alone.
 Stages of useContext
I. create context objects using React.createContext
II. Context Provider Accepts a value property to be passed to consuming components that are
descendants of this Provider.
III. ContextConsumer: The function receives the current context value and returns a React node.
• Generally, when we have two or more levels(height) in our component tree, it is viable to use a
store instead of passing props and then lifting the state as this will create confusion and
unnecessary lengthy code.
useRef
• The useRef Hook allows to persist values between renders.
• It can be used to store a mutable value that does not cause a re-render when updated.
• We can add a ref attribute to an element to access it directly in the DOM.
• It’s like a secret pocket of your component that React doesn’t track.
• When we initialize useRef we set the initial value: useRef(initialValue).
• useRef() only returns one item. It returns an Object called current.
let ref = useRef(0);
• The useRef Hook can also be used to keep track of previous state values.
• useRef can be a string, an object, or even a function.
• Use Case: When a component requires you to “remember” some information, but don’t want that
information to trigger new renders
• For example, you can use refs to store timeout IDs, DOM elements, and other objects that don’t
impact the component’s rendering output.
useRef vs state
useRef state
useRef(initialValue) returns { current:
initialValue }
useState(initialValue) returns the current
value of a state variable and a state setter function
( [value, setValue])
Doesn’t trigger re-render when changing it. Triggers re-render when changing it.
Mutable—m can modify and update the current value
outside of the rendering process.
“Immutable”— must use the state setting function to modify
state variables to queue a re-render.
You shouldn’t read (or write) the current value during
rendering.
You can read state at any time. However, each render has its
own snapshot of state which does not change.
useReducer
• It is similar to the useState Hook and allows for custom state logic.
• The useReducer Hook is the better alternative to the useState hook and is generally more
preferred over the useState hook when you have complex state-building logic or when the next
state value depends upon its previous value or when the components are needed to be optimized.
• The useReducer hook takes two arguments including reducer, and initial state, and returns the
current state and a dispatch method.
const [state, dispatch] = useReducer(reducer, initialArg, init?);
 Parameters
• reducer: The reducer is the user-defined function/method that takes the current state with the
dispatch method as argument to handle the state. State and action can be of any type.
• initialArg: It is the initial value to be pass in the hook. It can be a value of any type.
• optional init: The initializer function that should return the initial state. If it’s not specified, the
initial state is set to initialArg. Otherwise, the initial state is set to the result of calling init(initialArg).
 Returns an array with exactly two values:
• The current state. During the first render, it’s set to init(initialArg) or initialArg (if there’s no init).
• The dispatch function that lets you update the state to a different value and trigger a re-render.
Custom Hooks
• 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.
• For example, to fetch data, to keep track of whether the user is online, or to connect to a chat
room. We can create Hooks as per the application’s needs.
• Creating a custom hook is the same as creating a JavaScript function whose name starts with “use”.
• Custom hooks name should be starting with “use”, because without it React can’t realize that it is a
custom hook and therefore can’t apply the rules of hooks to it. So, you should name it starting with
“use”.
• It can use other hooks inside it, return anything you want it to return, and take anything as
parameters.
• After the Hooks have been introduced in React, code reusability has reached altogether a new
level.
• There are many Custom hooks available on npm which can be used in our Projects rather than
implementing our own one.
Additional Hooks
 useCallback: is a React Hook that lets you cache a function definition between re-renders.
const cachedFn = useCallback(fn, dependencies)
• React will compare the dependencies with the dependencies you passed during the previous
render. If none of the dependencies have changed, useCallback will return the same function as
before. Otherwise, useCallback will return the function you passed on this render.
 useDebugValue: is a React Hook that lets you add a label to a custom Hook in React Dev Tools.
useDebugValue(value, format?)
 useDeferredValue: is a React Hook that lets you defer updating a part of the UI. The deferred value
is “lag behind” the latest value.
const deferredValue = useDeferredValue(value)
 useId: is a React Hook for generating unique IDs that can be passed to accessibility attributes.
const id = useId()
 useInsertionEffect: This allows inserting elements into the DOM before any layout effects fire. This
is used to inject dynamic styles from CSS-in-JS libraries.
useInsertionEffect(setup, dependencies?)
Babel
Babel
• Babel is a powerful JavaScript compiler that allows us to use future JavaScript in today’s browsers.
• A compiler is a tool that is used to convert source code into another source code that is of the same level.
• Babel can convert the latest version of JavaScript code into the one that the browser understands.
• The latest standard version that JavaScript follows is ES2020 which is not fully supported by all browsers.
• Babel with React to compiler the JSX code into simple React functions that can be understood by browsers.
 Manually setup Babel in React with Webpack
1. Navigate to the folder in cmd. mkdir react-babel-app-learning cd react-babel-app-
learning
2. Execute command in cmd npm init –y
3. Install the necessary react packages using the command npm i react react-dom
4. Install webpack and babel using the command npm i webpack webpack-cli @babel/core
@babel/preset-env @babel/preset-react babel-loader html-webpack-plugin
webpack-dev-server –save-dev
5. Create the files named index.html, App.js, index.js, webpack.config.js, .babelrc and
add code
6. Inside the scripts section of the package.json file add code.
7. To run the application type the following command in a web browser npm start. This will start
application on port 8080 by default.
Some Interview Questions
package.json vs package-lock.json
 package.json is a versioning file that is used to install multiple packages in the React project.
 package-lock.json is crucial for locking dependencies to specific versions, ensuring consistent installations
across different environments. Without it, variations in installed versions may occur. This file guarantees
reproducibility by specifying exact versions, preventing discrepancies.
 Including both `package.json` and `package-lock.json` in source control ensures that collaborators install the
exact dependencies, maintaining uniformity.
package.json package-lock.json
It contains basic information about the project. Like name,
description, author, script, and dependencies.
It contains the name, dependencies, and locked version of
the project and describes the exact tree that was generated
to allow subsequent installs to have the identical tree.
It records important metadata about the project. It allows future devs to install the same dependencies in the
project.
It lists the required dependencies and their version ranges,
but not the exact versions to be installed.
It is used to ensure that the same dependencies are installed
consistently across different environments and prevent
conflicts due to different versions being installed.
It can be easily shared and committed to version control
systems.
It is not meant to be manually modified and should be
committed to the version control system to ensure
consistency across all team members.
Why React is Unidirectional
 Unidirectional data flow: It is a technique that means the data has one, and only one way to be transferred to
other parts of the application.
• The data from the parent is known as props. You can only transfer data from parent to child and not vice
versa.
• This means that the child components cannot update or modify the data on their own, making sure that a
clean data flow architecture is followed. This also means that you can control the data flow better.
Why React is called a Single Page Application
 Single Page Application (SPAs): This only needs to update the currently shown page in order to respond to
the user, eliminating the need to repeatedly load pages from the server. This approach avoids interrupting the
user experience between successive pages, making the application behave more like a desktop application.
• All necessary code, such as HTML, JavaScript, and CSS, is retrieved with a single page load in a SPA. The
appropriate resources are dynamically loaded and added to the page as necessary while allowing navigation
via link clicks or other interactive elements without requiring full reloads of content.
• All pages are connected at a single root (i.e. index.js).
 Multi-page application (MPA): It is a type of traditional web application that consists of several pages with its
own URL and loads independently from the server when accessed.
• Users can request an HTML page rendered in their browser by clicking a link or typing a URL into the address
bar, which the server processes. Since the server is responsible for creating and delivering the HTML page
whenever a new page is loaded, the server must make a new request to the client.
Deployment
Deploy React App using Git Hub Page
• GitHub: A code hosting platform for collaboration and version control. It is used to work and store web
development projects.
• GitHub Pages: It allows you to turn your GitHub repositories into an elegant website to showcase your
portfolio, projects, documentation, or anything else you want to make live but remember that there is no
database to set up and no server to configure.
 Steps to deploy React Application on Git Hub Page
1. Commit app code to Git.
2. Install the gh-pages package as a “dev-dependency” of the app using the command npm install --
save gh-pages
3. Add properties “homepage”:”http://{username}.github.io/{repo-name}” to the
app’s package.json file. Ex. http://KPCodeLearning.github.io/React-Learning-App
4. Add some properties in the script in package.json.
5. If the git folder does not exist in the project, Create a git repository in the app’s folder and add the GitHub
repository as a “remote” in your local git repository.
6. Execute command npm run deploy
7. Check on browser https://kpcodelearning.github.io/React-Learning-App/
Thanks for the Attention...
Happy Coding...
https://github.com/KPCodeLearning/React-Learning-App
https://kpcodelearning.github.io/React-Learning-App/
https://www.linkedin.com/in/karmanjayverma/

More Related Content

Similar to React JS; all concepts. Contains React Features, JSX, functional & Class component, Router, Hooks etc.

Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & AnswerMildain Solutions
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react reduxRajesh Kumar
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperFabrit Global
 
React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?Fibonalabs
 
FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxEhtesham46
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Flipkart
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptBOSC Tech Labs
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?BOSC Tech Labs
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptxNavneetKumar111924
 

Similar to React JS; all concepts. Contains React Features, JSX, functional & Class component, Router, Hooks etc. (20)

React
ReactReact
React
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
Intro to React.js
Intro to React.jsIntro to React.js
Intro to React.js
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
ReactJs
ReactJsReactJs
ReactJs
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & Answer
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?
 
FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptx
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state ppt
 
React js
React jsReact js
React js
 
React
ReactReact
React
 
React a11y-csun
React a11y-csunReact a11y-csun
React a11y-csun
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?
 
Presentation1
Presentation1Presentation1
Presentation1
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 

Recently uploaded

ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfFIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdfMuhammad Subhan
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 

Recently uploaded (20)

ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 

React JS; all concepts. Contains React Features, JSX, functional & Class component, Router, Hooks etc.

  • 3. React JS Features • React is an Open Source JavaScript library used for creating dynamic and interactive user interfaces for mobile and web applications. • It is highly flexible, declarative, and efficient for developing scalable, simple, and fast front- end for web and mobile applications. • React is only concerned with rendering data to the Document Object Model (DOM) and so creating React applications usually requires the use of additional libraries for implementing things like state management and routing. • DOM: Document Object Model is a way to represent the webpage in a structured hierarchical way. With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or Elements of HTML using commands or methods provided by the Document object. Using DOM, JavaScript gets access to HTML as well as CSS of the web page and can also add behavior to the HTML elements. • Virtual DOM: Virtual DOM exists which is like a lightweight copy of the actual DOM. So for every object that exists in the original DOM, there is an object for that in React Virtual DOM. It is exactly the same, but it does not have the power to directly change the layout of the document. Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets drawn on the screen.
  • 4. React JS Features • Components: The component is the most basic building block of the React Application UI. • One-way data-binding: React JS follows one-way data binding or unidirectional data flow that gives better control throughout the application. • JSX: React uses JSX for building templates instead of regular JavaScript. JSX is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript.
  • 6. JSX • JavaScript XML: JSX is basically a syntax extension of JavaScript. It helps us to write HTML in JavaScript and forms the basis of React Development. • JSX creates an element in React that gets rendered in the UI. It is transformed into JavaScript functions by the compiler at runtime. • Error handling and warnings become easier to handle when using JSX • Ex: const elem = <h1>This is sample JSX</h1>
  • 7. Create a New Application in React
  • 8. Create New App • There are basically two methods for React JS Environment Setup • Using create-react-app • Using webpack and babel • Create React using create-react-app 1. Install Node.js 2. Run: npx create-react-app app-name 3. If the command is not working run npm install create-react-app 4. New app has been created in ./app-name 5. Move to folder cd app-name 6. Run the command npm install to install all dependencies from package.json 7. Run the command npm start to view on the localhost:3000 by default. 8. When you’re ready to launch your app, run this command npm run build to prepare bundles. 9. This command will build the react app and bundle the app into CSS/JS/HTML files and put them in the /build folder
  • 9. Change listening PORT  Update package.Json with the below code and run the application "scripts": { "start": "set PORT=5000 && react-scripts start" }  Add a .env file in the project root and update the file with the below code. PORT=5000
  • 10. Anatomy of a new React app
  • 13. Components • Components are the building blocks of any React app. These blocks are reusable and independent like functions in JavaScript and are responsible for representing the elements on the Web Page. • Components in React basically return a piece of JSX code that tells what should be rendered on the screen. • The name of a component should always start with a capital letter. This is done to differentiate a component tag from HTML tags. • A component is the combination of • Template using HTML • User Interactivity using JS • Applying Styles using CSS
  • 14. Functional Components • It is simply a Javascript function. These functions may or may not receive data as parameters • Use functional components only when we are sure that our component does not require interaction or work with any other component.
  • 15. Class Components • The class components are a little more complex than the functional components. • Class components are reusable. • We can pass data from one class component to another class component. • Where to use class components: 1. Managing State of the Components 2. Adding Life Cycle Methods to Components 3. Need to Write Logic for Event Handlers
  • 16. Functional vs Class Components Functional Components Class Components It is a plain JavaScript pure function that accepts props as an argument and returns a JSX element. It requires to extend from React.Component and create a render function that returns a React element. Functional components run from top to bottom and once the function is returned it can’t be kept alive. The class component is instantiated and different life cycle method is kept alive and is run and invoked depending on the phase of the class component. Stateless components as they simply accept data and display them in some form, they are mainly responsible for rendering UI. Stateful components because they implement logic and state. Hooks can be used in functional components to make them Stateful. this keyword is required, along with the setState() function and a constructor. A constructor is not supported by functional components Provide a constructor for storing state before passing props to the parent class
  • 18. props • React allows to passing information to a Component using properties i.e. called props. • Props are objects which can be used inside a component. • The ‘this.props’ is a global object that stores all of a component’s props. • To access a prop from a function, we no longer need to use the ‘this’ keyword. Functional components accept props as parameters and can be accessed directly. • Props are read-only. • propTypes: PropTypes.string, PropTypes.bool, PropTypes.array, PropTypes.anyOtherType
  • 19. state • React introduces, a new concept named “state” which allows React components to change their output over time in response to user actions without violating this rule. • State is similar to props, but it is private and fully controlled by the component. • The state of a component is an object that contains data specific to a given component that may change over time. • The state is user user-defined plain javascript object. • Props are immutable i.e. once set the props cannot be changed, while State is an observable object that may change over time. • States can be used in Class Components but in Functional components we have to use React hooks(useState) to implement states. • While Props are set by the parent component, the State is generally updated by event handlers.
  • 20. Conventions to use state • State must have some initial value that needs to define the constructor of the component’s class. • The state should never be updated explicitly. React uses an observable object as the state that observes what changes are made to the state and helps the component behave accordingly. • The only time we are allowed to define the state explicitly is in the constructor to provide the initial state. • setState() method is the in-build method in React to update the state. setState() method takes a single parameter and expects an object that should contain the set of values to be updated. Once the update is done the method implicitly calls the render() method to view the page. • State updates should be independent. The state object of a component may contain multiple attributes and React allows to use setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently.
  • 21. Prop vs state props State props are used to transfer data from a parent component to a child states are used to manage the data inside a component itself. Props are immutable and cannot be changed within a component state is mutable and can be updated using the setState function. Props can be used with state and functional components. The state can be used only with the state components/class component Props are read-only. The state is both read and write. Props are passed down from the parent component and are read-only within the child component state is only accessible within the component where it is defined. Props can be used to customize the behavior or appearance of a component state is used to keep track of information that can change over time.
  • 22. Events • React has the same events as HTML: click, change, mouseover etc.  Adding Events • React events are written in camelCase syntax: onClick • React event handlers are written inside curly braces: onClick={methodname}  Passing Arguments • To pass an argument to an event handler, use an arrow function.  React Event Object • Event handlers have access to the React event that triggered the function.
  • 24. Lifecycle of Components • Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. • React components can go through four stages of their life • Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class. • Mounting: Mounting means putting elements into the DOM or adding a new component to the screen. • Updating: Updating is the stage when the state of a component is updated and the application is repainted. • Unmounting: It is the final step of the component lifecycle where the component is removed from the page.
  • 25. Initialization • In this phase, the props and initial state of the component are mentioned. this is generally done in the constructor of the component.  constructor: • When implementing the constructor for a React.Component subclass (parent class), we should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. • React constructors are only used for two purposes: • Initializing local state by assigning an object to this.state. • Binding event handler methods. • Super() function is to call the constructor of the parent class. It is used when we need to access a few variables in the parent class. It returns an object which represents the parent class. • super(props) can be called if needed to access this.props in the constructor. • We should not call setState() in the constructor. Constructor is the only place where we should assign this.state directly. In all other methods, we need to use this.setState() instead.
  • 26. Mounting • Mounting means putting elements into the DOM. • The render() method is required and will always be called, the others are optional and will be called if you define them. • React has four in-built methods that get called, in this order, when mounting a component.  constructor(): The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values.  getDerivedStateFromProps() : The getDerivedStateFromProps() method is called right before rendering the element(s) in both mounting and updating phase in React. • It takes updated props and the current state as arguments and returns an object with changes to the state. • This is the natural place to set the state object based on the initial props.  render(): The render() method is required and is the method that outputs the HTML to the DOM.  componentDidMount(): The componentDidMount() method is called after the component is rendered. • All the AJAX requests and the DOM or state update should be coded in this method.
  • 27. Updating • A component is updated whenever there is a change in the component's state or props. • React has five built-in methods that get called, in this order, when a component is updated: getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate  getDerivedStateFromProps: This is the first method that is called when a component gets updated. This method gets called just before rendering.  shouldComponentUpdate: shouldComponentUpdate() method returns a Boolean value that specifies whether React should continue with the rendering or not. • Component will update if the value is true and the default value is true.  render: The render() method is called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.
  • 28. Updating • Render method returns one of the following types: • React elements • Arrays and fragments. • Portals • String and numbers. • Booleans or null.  getSnapshotBeforeUpdate: The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated. • Any value returned by getSnapshotBeforeUpdate() method will be used as a parameter for componentDidUpdate() method. • This function is always used along with the componentDidUpdate() method but vice-versa isn’t true. • If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise, you will get an error.  componentDidUpdate: This method is called immediately after the component is updated in the DOM. • The componentDidUpdate() is called after componentDidMount() and can be useful to perform some action when the state of the component changes. • This method can be used to execute the event when the component is visible on the DOM.
  • 29. Unmounting • When switches from one Component to another Component on the UI, the Previous component gets removed from the DOM, and the new Component contents will be displayed in the UI. • React has only one built-in method that gets called when a component is unmounted.  componentWillUnmount: The componentWillUnmount() method is called when the component is about to be removed from the DOM. • componentWillUnmount() can be called when we want to Perform any necessary cleanup required, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().
  • 32. Router • React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL also used to track the content that the user is trying to view. • Create React App doesn't include page routing. To install react-router in the application run command npm i react-router-dom in the terminal. And import this npm to the component. This installation will add router package details in the package.json.  React Router Components: • Router Type (BrowserRouter, MemoryRouter, HashRouter): It is the parent component that is used to store all of the other components. • Routes: It’s a new component introduced in the v6 and an upgrade of the component. The main advantages of Routes over Switch are: • Routes are chosen based on the best match instead of being traversed in order. • Route: Route is the conditionally shown component that renders some UI when its path matches the current URL. • Link: The link component is used to create links to different routes and implements navigation around the application. It works like an HTML anchor tag.
  • 33. Types of Router  Browser Router • It uses HTML 5 history API (i.e. pushState, replaceState, and popState API) to keep your UI in sync with the URL. • It keeps the URL’s history and writes to address bar on click of browser’s back and forward button. • It routes as a normal URL in the browser and assumes that the server is handling all the request URLs (eg., /, /about) and points to root index.html.  Memory Router • It keeps the history of the URL in memory and it does not read or write to the address bar so the user can not use the browser’s back button as well as the forward button. • It doesn’t change the URL in your browser. It is very useful for testing and non-browser environments like React Native.  Hash Router • Hash router uses client-side hash routing. • It uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL. • The hash portion of the URL won’t be handled by the server, the server will always send the index.html for every request and ignore the hash value. • It doesn’t need any configuration in the server to handle routes.
  • 35. React Hooks • Hooks allow function components to have access to state, lifecycle methods, and other React features. Because of this, class components are generally no longer needed. • Hooks were added to React in version 16.8. • Hooks provides a direct API to react concepts such as props, state, context, refs, and life-cycle. • You must import Hooks from react. • Hooks cannot be used with class components • If have stateful logic that needs to be reused in several components, Custom Hooks can be built.  Why the need for Hooks? • Use of ‘this’ keyword • Reusable stateful logic • Simplifying complex scenarios  Rules for using hooks • Only functional components can use hooks. • Calling of hooks should always be done at the top level of components. • Hooks should not be inside conditional statements.
  • 36. Classes vs React Hooks Aspect Hooks Class Syntax Hooks use regular JavaScript functions Classes use the class syntax with `extends React.Component`. State Management The useState hook is used with hooks to define and update state variables. In classes, the state is defined using the `this.state` object and updated with `this.setState()`. Lifecycle Methods The `useEffect` hook in hooks is used to handle related lifecycle events. To handle component lifecycle events, classes contain lifecycle methods such as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`. Code Organization Hooks allow you to group together relevant logic by breaking it into smaller custom hooks. With classes, relevant logic and state are frequently dispersed over many lifecycle methods and class methods. Reusability Hooks encourage reuse by allowing you to design custom hooks that encapsulate a group of related functionalities. Classes can be reused by using higher-order components (HOCs) or render properties. Learning Curve Hooks came into use later and offer a simpler and more logical approach to writing React has had classes since its early versions, therefore there are more instructional materials and code samples
  • 37. Classification of React Hooks • Hooks in React are Classified into Basic Hooks and Additional Hooks.  Basic Hooks • useState • useEffect • useContext  Additional Hooks • useReducer • useCallback • useMemo • useRef • useImperativeHandle • useLayoutEffect • useDebugValue
  • 38. useState Hook • The React useState Hook allows us to track the state in a function component. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together. • State generally refers to data or properties that need to be tracked in an application. • This allows one to declare a state variable inside a function. • useState accepts an initial state and returns two values, The current state and a function that updates the state. • The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these! • When the state of the object is updated, the entire state gets overwritten, use the JavaScript spread operator to update a particular object item.
  • 39. useEffect Hook • The useEffect hook in React is used to handle the side effects in React such as fetching data, updating DOM and timers. • This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering. • The useEffect hook accepts two arguments where the second argument is optional useEffect(<function>, <dependency>) • This Hooks is capable of handling componentDidMount(), componentDidUpdate(), and componentWillUnmount() life-cycle methods of class-based components into the functional components. • We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array.  Ways of controlling side effects in useEffect hook • To run useEffect on every render do not pass any dependency • To run useEffect only once on the first render pass any empty array in the dependency • To run useEffect on change of a particular value. Pass the state and props in the dependency array
  • 40. Lifecycle methods using useEffect  For componentDidMount  For componentDidUpdate  For componentWillUnmount
  • 41. useContext • React Context is a way to manage the state globally. Context is primarily used when some data needs to be accessible by many components at different nesting levels. • React Context is a method to pass props from parent to child component(s), by storing the props in a store and using these props from the store by child component(s) without actually passing them manually at each level of the component tree. • It can be used with the useState Hook to share the state between deeply nested components more easily than with useState alone.  Stages of useContext I. create context objects using React.createContext II. Context Provider Accepts a value property to be passed to consuming components that are descendants of this Provider. III. ContextConsumer: The function receives the current context value and returns a React node. • Generally, when we have two or more levels(height) in our component tree, it is viable to use a store instead of passing props and then lifting the state as this will create confusion and unnecessary lengthy code.
  • 42. useRef • The useRef Hook allows to persist values between renders. • It can be used to store a mutable value that does not cause a re-render when updated. • We can add a ref attribute to an element to access it directly in the DOM. • It’s like a secret pocket of your component that React doesn’t track. • When we initialize useRef we set the initial value: useRef(initialValue). • useRef() only returns one item. It returns an Object called current. let ref = useRef(0); • The useRef Hook can also be used to keep track of previous state values. • useRef can be a string, an object, or even a function. • Use Case: When a component requires you to “remember” some information, but don’t want that information to trigger new renders • For example, you can use refs to store timeout IDs, DOM elements, and other objects that don’t impact the component’s rendering output.
  • 43. useRef vs state useRef state useRef(initialValue) returns { current: initialValue } useState(initialValue) returns the current value of a state variable and a state setter function ( [value, setValue]) Doesn’t trigger re-render when changing it. Triggers re-render when changing it. Mutable—m can modify and update the current value outside of the rendering process. “Immutable”— must use the state setting function to modify state variables to queue a re-render. You shouldn’t read (or write) the current value during rendering. You can read state at any time. However, each render has its own snapshot of state which does not change.
  • 44. useReducer • It is similar to the useState Hook and allows for custom state logic. • The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized. • The useReducer hook takes two arguments including reducer, and initial state, and returns the current state and a dispatch method. const [state, dispatch] = useReducer(reducer, initialArg, init?);  Parameters • reducer: The reducer is the user-defined function/method that takes the current state with the dispatch method as argument to handle the state. State and action can be of any type. • initialArg: It is the initial value to be pass in the hook. It can be a value of any type. • optional init: The initializer function that should return the initial state. If it’s not specified, the initial state is set to initialArg. Otherwise, the initial state is set to the result of calling init(initialArg).  Returns an array with exactly two values: • The current state. During the first render, it’s set to init(initialArg) or initialArg (if there’s no init). • The dispatch function that lets you update the state to a different value and trigger a re-render.
  • 45. Custom Hooks • 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. • For example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. We can create Hooks as per the application’s needs. • Creating a custom hook is the same as creating a JavaScript function whose name starts with “use”. • Custom hooks name should be starting with “use”, because without it React can’t realize that it is a custom hook and therefore can’t apply the rules of hooks to it. So, you should name it starting with “use”. • It can use other hooks inside it, return anything you want it to return, and take anything as parameters. • After the Hooks have been introduced in React, code reusability has reached altogether a new level. • There are many Custom hooks available on npm which can be used in our Projects rather than implementing our own one.
  • 46. Additional Hooks  useCallback: is a React Hook that lets you cache a function definition between re-renders. const cachedFn = useCallback(fn, dependencies) • React will compare the dependencies with the dependencies you passed during the previous render. If none of the dependencies have changed, useCallback will return the same function as before. Otherwise, useCallback will return the function you passed on this render.  useDebugValue: is a React Hook that lets you add a label to a custom Hook in React Dev Tools. useDebugValue(value, format?)  useDeferredValue: is a React Hook that lets you defer updating a part of the UI. The deferred value is “lag behind” the latest value. const deferredValue = useDeferredValue(value)  useId: is a React Hook for generating unique IDs that can be passed to accessibility attributes. const id = useId()  useInsertionEffect: This allows inserting elements into the DOM before any layout effects fire. This is used to inject dynamic styles from CSS-in-JS libraries. useInsertionEffect(setup, dependencies?)
  • 47. Babel
  • 48. Babel • Babel is a powerful JavaScript compiler that allows us to use future JavaScript in today’s browsers. • A compiler is a tool that is used to convert source code into another source code that is of the same level. • Babel can convert the latest version of JavaScript code into the one that the browser understands. • The latest standard version that JavaScript follows is ES2020 which is not fully supported by all browsers. • Babel with React to compiler the JSX code into simple React functions that can be understood by browsers.  Manually setup Babel in React with Webpack 1. Navigate to the folder in cmd. mkdir react-babel-app-learning cd react-babel-app- learning 2. Execute command in cmd npm init –y 3. Install the necessary react packages using the command npm i react react-dom 4. Install webpack and babel using the command npm i webpack webpack-cli @babel/core @babel/preset-env @babel/preset-react babel-loader html-webpack-plugin webpack-dev-server –save-dev 5. Create the files named index.html, App.js, index.js, webpack.config.js, .babelrc and add code 6. Inside the scripts section of the package.json file add code. 7. To run the application type the following command in a web browser npm start. This will start application on port 8080 by default.
  • 50. package.json vs package-lock.json  package.json is a versioning file that is used to install multiple packages in the React project.  package-lock.json is crucial for locking dependencies to specific versions, ensuring consistent installations across different environments. Without it, variations in installed versions may occur. This file guarantees reproducibility by specifying exact versions, preventing discrepancies.  Including both `package.json` and `package-lock.json` in source control ensures that collaborators install the exact dependencies, maintaining uniformity. package.json package-lock.json It contains basic information about the project. Like name, description, author, script, and dependencies. It contains the name, dependencies, and locked version of the project and describes the exact tree that was generated to allow subsequent installs to have the identical tree. It records important metadata about the project. It allows future devs to install the same dependencies in the project. It lists the required dependencies and their version ranges, but not the exact versions to be installed. It is used to ensure that the same dependencies are installed consistently across different environments and prevent conflicts due to different versions being installed. It can be easily shared and committed to version control systems. It is not meant to be manually modified and should be committed to the version control system to ensure consistency across all team members.
  • 51. Why React is Unidirectional  Unidirectional data flow: It is a technique that means the data has one, and only one way to be transferred to other parts of the application. • The data from the parent is known as props. You can only transfer data from parent to child and not vice versa. • This means that the child components cannot update or modify the data on their own, making sure that a clean data flow architecture is followed. This also means that you can control the data flow better.
  • 52. Why React is called a Single Page Application  Single Page Application (SPAs): This only needs to update the currently shown page in order to respond to the user, eliminating the need to repeatedly load pages from the server. This approach avoids interrupting the user experience between successive pages, making the application behave more like a desktop application. • All necessary code, such as HTML, JavaScript, and CSS, is retrieved with a single page load in a SPA. The appropriate resources are dynamically loaded and added to the page as necessary while allowing navigation via link clicks or other interactive elements without requiring full reloads of content. • All pages are connected at a single root (i.e. index.js).  Multi-page application (MPA): It is a type of traditional web application that consists of several pages with its own URL and loads independently from the server when accessed. • Users can request an HTML page rendered in their browser by clicking a link or typing a URL into the address bar, which the server processes. Since the server is responsible for creating and delivering the HTML page whenever a new page is loaded, the server must make a new request to the client.
  • 54. Deploy React App using Git Hub Page • GitHub: A code hosting platform for collaboration and version control. It is used to work and store web development projects. • GitHub Pages: It allows you to turn your GitHub repositories into an elegant website to showcase your portfolio, projects, documentation, or anything else you want to make live but remember that there is no database to set up and no server to configure.  Steps to deploy React Application on Git Hub Page 1. Commit app code to Git. 2. Install the gh-pages package as a “dev-dependency” of the app using the command npm install -- save gh-pages 3. Add properties “homepage”:”http://{username}.github.io/{repo-name}” to the app’s package.json file. Ex. http://KPCodeLearning.github.io/React-Learning-App 4. Add some properties in the script in package.json. 5. If the git folder does not exist in the project, Create a git repository in the app’s folder and add the GitHub repository as a “remote” in your local git repository. 6. Execute command npm run deploy 7. Check on browser https://kpcodelearning.github.io/React-Learning-App/
  • 55. Thanks for the Attention... Happy Coding... https://github.com/KPCodeLearning/React-Learning-App https://kpcodelearning.github.io/React-Learning-App/ https://www.linkedin.com/in/karmanjayverma/