0% found this document useful (0 votes)
8 views72 pages

React JS Notes

This document provides an overview of React JS, a popular JavaScript library for building interactive user interfaces, particularly for single-page applications. It explains key concepts such as the difference between libraries and frameworks, the Virtual DOM, and the component-based architecture of React. Additionally, it covers how to add React to a website, the importance of JSX, and the execution flow of components.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views72 pages

React JS Notes

This document provides an overview of React JS, a popular JavaScript library for building interactive user interfaces, particularly for single-page applications. It explains key concepts such as the difference between libraries and frameworks, the Virtual DOM, and the component-based architecture of React. Additionally, it covers how to add React to a website, the importance of JSX, and the execution flow of components.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

React JS Notes

UNIT - IV

Introduction to React
What is ReactJS?
●​ React JS is a popular JavaScript library used to build interactive user interfaces
(UI)—especially for single-page applications (SPAs).

●​ React is used to build the user interface (UI) — what users see and interact with
in the browser.

●​ It runs on the client-side (frontend), not on the server.

1. What is a Library?
●​ A library is a collection of pre-written code that developers use to perform
common tasks without writing everything from scratch.

●​ The core purpose of a library is to:


●​ Save time
●​ Reduce effort
●​ Avoid repeating code
●​ Simplify complex tasks
2

What is JavaScript Framework

A JavaScript framework is a pre-defined structure or platform that provides a complete


foundation for developing applications, where the framework controls the flow of the
program and developers build their code within its rules.

Key Points

●​ The framework controls the application flow (Inversion of Control)


●​ Provides architecture and structure
●​ Used to build entire applications
●​ Follows specific rules/patterns

Library Framework

Collection of reusable functions Complete structure for development

Developer controls flow Framework controls flow

Used for specific tasks Used to build full applications

Example: jQuery Example: Angular

2. Interactive user interface(UI)

Example : Click a button to update text on the page

i. HTML with JS
<!DOCTYPE html>​
<html>​
<body>​
<div>
3

<h1 id="title">Hello</h1>​
<button onclick="changeText()">Click Me</button>
</div>​
<script>​
function changeText() {​
[Link]("title").innerHTML = "Hello Teja!";​
}​
</script>​
</body>​
</html>

Without React: You manually update the DOM

ii. With React


import { useState } from "react";​

function App() {​
const [text, setText] = useState("Hello");​

return (​
<div>​
<h1>{text}</h1>​
<button onClick={() => setText("Hello Teja!")}>​
Click Me​
</button>​
</div>​
);​
}​
export default App;

With React: UI updates automatically using components

Question: How does React update a specific <h1> element when a button is clicked,
especially if there are multiple <h1> tags in the component?

In React, the button does NOT “find” the <h1> tag at all

There is:
4

●​ No getElementById
●​ No DOM searching

Instead, React uses state + re-rendering

How React Actually Works

const [text, setText] = useState("Hello");​



<h1>{text}</h1>​
<button onClick={() => setText("Hello Teja!")}>

Flow:

1.​ text = "Hello" → React renders <h1>Hello</h1>


2.​ Button is clicked
3.​ setText("Hello Teja!") updates state
4.​ React re-renders the component
5.​ <h1>{text}</h1> becomes <h1>Hello Teja!</h1>

React updates UI based on data (state) — not by selecting elements.

What if there are multiple <h1> tags?


function App() {​
const [text, setText] = useState("Hello");​

return (​
<div>​
<h1>{text}</h1>​
<h1>Static Heading</h1>​

<button onClick={() => setText("Updated!")}>​
Click Me​
</button>​
</div>​
);​
}
5

What happens?
●​ First <h1> → uses {text} → will update
●​ Second <h1> → static → will NOT change

Because only the first one is linked to state

Important Concept

React doesn’t update elements​


React updates state data → then UI automatically follows

Frontend JS React Library

Find element manually No need to find

Update specific element Update state

DOM manipulation Declarative UI

Instead of directly updating the browser DOM (which is slow), React updates this virtual
DOM copy first, then efficiently applies only the necessary changes to the real DOM.

What is the Virtual DOM?

The Virtual DOM (VDOM) is a lightweight JavaScript copy of the real DOM.
6

Why Virtual DOM is Fast


●​ Real DOM updates are expensive
●​ Virtual DOM operations are fast (in memory)
●​ React updates only what changed, not the whole page

<h1>{text}</h1>
●​ Before: <h1>Hello</h1>
●​ After: <h1>Hello Teja!</h1>

React updates only the text inside <h1>, not the whole element
7

React follows:
“Compare → Find difference → Update only that part”

Step-by-Step Working (Reconciliation Process)

1.​ Initial Render


○​ React creates a Virtual DOM tree from your components
2.​ State Change
○​ Example: setText("Hello Teja!")
3.​ New Virtual DOM Created
○​ React creates a new VDOM snapshot
4.​ Diffing (Comparison)
○​ React compares old VDOM vs new VDOM
5.​ Minimal Updates
○​ Only changed elements are updated in the real DOM

This process is called Reconciliation


8
9

3. What is a Single Page Application (SPA)?

A Single Page Application is a web application that:

●​ Loads only one HTML page initially


●​ Updates content dynamically without reloading the entire page
●​ Uses JavaScript to change views

How React relates to SPA

React helps you build SPAs because:

●​ It updates only parts of the UI (using Virtual DOM)


●​ It avoids full page reloads
●​ It creates a smooth, app-like experience
10

Core Features of React

React is popular because of a few powerful core features that make UI development
fast and scalable

1. Component-Based Architecture

●​ UI is split into small reusable components


●​ Each component has its own logic and UI

Example: Navbar, Footer, Button, Card

Reuse components anywhere → less code

2. Virtual DOM

●​ React uses a Virtual DOM (in-memory copy of real DOM)


●​ Updates only changed parts instead of full page

Improves performance significantly

3. JSX (JavaScript XML)

●​ Allows writing HTML inside JavaScript

const element = <h1>Hello Teja</h1>

Makes code readable and easy to write

4. Unidirectional Data Flow

●​ Data flows one way (parent → child)

Easier debugging and predictable behavior

5. Hooks (Modern Feature)

●​ Functions that let you use state and lifecycle in functional components
11

Example: const [count, setCount] = useState(0);

Cleaner and more powerful than class components

6. State Management

●​ React manages dynamic data using state

UI updates automatically when state changes

7. Reusability

●​ Components can be reused across the app

Faster development and consistency

8. Strong Ecosystem

●​ Works with many libraries/tools:


○​ Routing
○​ State management
○​ API handling

Flexible and scalable

9. Declarative UI

●​ You describe what UI should look like


●​ React handles how to update it

Less manual DOM manipulation

10. Cross-Platform (via React Native)

●​ Use React concepts to build mobile apps

Same logic for web + mobile


12

Why do you learn React?


Before React, front-end development struggled with:

●​ Manual DOM Manipulation: Traditional JavaScript directly modified


the DOM, slowing down the performance.
●​ Complex State Management: Maintaining UI state became messy
and hard to debug.

[Link] library History

●​ The latest version of [Link] is 19.2 (05 December 2024).


●​ Initial release to the Public (version 0.3.0) was in July 2013.
●​ [Link] was first used in 2011 for Facebook's Newsfeed feature.
●​ Facebook Software Engineer, Jordan Walke, created it.

4.2 Add React to a website

Method 1: Add React via CDN (Quick & Simple)

Best for: learning, small demos, existing static websites

Step 1: Create an HTML file


<!DOCTYPE html>​
<html>​
<head>​
<title>React CDN Example</title>​
</head>​
<body>​
<div id="root"></div>​
</body>​
</html>
13

Step 2: Add React & ReactDOM CDN

Add these inside <body> before closing tag:

<!-- React -->​


<script
src="[Link]

<!-- React DOM -->​
<script
src="[Link]
cript>​

<!-- Babel (for JSX support) -->​
<script
src="[Link]

Step 3: Write React Code


<script type="text/babel">​
function App() {​
return <h1>Hello React </h1>;​
}​

const root = [Link]([Link]('root'));​
[Link](<App />);​
</script>

What happens here?

●​ React creates Virtual DOM


●​ React compares changes (diffing)
●​ Only updates necessary parts in Real DOM

4.3 Method 2: Add React using Vite (Recommended Modern


Way)
14

Best for: real projects, performance, scalability

Step 1: Install [Link]

Download from: [Link]

Check:

node -v​
npm -v

Step 2: Create React App with Vite


npm create vite@latest my-react-app
Choose:

●​ Framework → React
●​ Variant → JavaScript

Step 3: Navigate to project


cd my-react-app

Step 4: Install dependencies


npm install
15

Step 5: Run project


npm run dev

Open browser: [Link]


16

Project Structure
my-react-app/

├── [Link]

├── [Link]

├── src/

│ ├── [Link]

│ ├── [Link]

│ └── assets/

Important Files

[Link]

import React from 'react'​


import ReactDOM from 'react-dom/client'​
import App from './[Link]'​

[Link]([Link]('root')).render(​
<[Link]>​
<App />​
</[Link]>,​
)

[Link]

function App() {​
return <h1>Hello React</h1>;​
}​

export default App;
17

Method 3: Add React to Existing Website


If you already have HTML/CSS/JS site

Option A: Add React to a section


<div id="react-widget"></div>​

<script type="text/babel">​
function Widget() {​
return <button>Click Me</button>;​
}​

[Link]([Link]('react-widget')).render(<
Widget />);​
</script>

Option B: Gradual Migration


●​ Keep existing pages
●​ Replace parts with React components
●​ Convert page-by-page

Key Concepts You Must Know

1. JSX

2. Components

3. Props

4. State
18

4.4 Introducing JSX


JSX stands for JavaScript XML and is a syntax extension that allows writing HTML-like
code inside JavaScript.

Example:

const element = <h1>Hello, JSX!</h1>;

●​ <h1>Hello, JSX!</h1> is a JSX element, similar to HTML, that


represents a heading tag.
●​ JSX is converted into JavaScript behind the scenes, where React uses
[Link]() to turn the JSX code into actual HTML elements
that the browser can understand.
●​ browsers do NOT understand JSX directly — it must be transformed
into regular JavaScript before execution.

PipeLine:

JSX Code​
↓​
Transpiler​
↓​
JavaScript​
↓​
Virtual DOM​
↓​
Diffing Algorithm​
↓​
Real DOM (Browser UI)
19

Step 1: Write JSX Code

const element = <h1>Hello, JSX!</h1>;

This looks like HTML but is actually not valid JavaScript. browsers do NOT
understand JSX directly.

Step 2: Transpilation (Conversion) source-to-source compiler

Tools like:

●​ Babel
●​ Vite

convert JSX into plain JavaScript.

Two Types of JSX Transformation


(A) Classic Transform (React < 17)
const element = <h1>Hello JSX!</h1>;

[Link](type, props, ...children)

Type: html tags

Props: properties

Children: inside of the open tag and closing tag

Transformed into:

const element = [Link]("h1", null, "Hello JSX!");


●​ null means : No properties (no attributes, no styles, no class, nothing)

const element = <h1 className="title">Hello JSX!</h1>


20

Transformed into

[Link]("h1", { className: "title" }, "Hello JSX!” );

Requires: import React from "react";

(B) Automatic Transform (React 17+)

React introduced a new JSX transform using a special module:

"react/jsx-runtime"

Modern React uses:

●​ _jsx() → single child


●​ _jsxs() → multiple children

const element = <h1>Hello JSX!</h1>;

Transformed into:

import { jsx as _jsx } from "react/jsx-runtime";​



const element = _jsx("h1", { children: "Hello" });

No direct use of React

●​ Old: [Link](...) → needs React


●​ New: _jsx(...) → does NOT use React variable

So import React is unnecessary

Multiple childrens: must use <div> tag

<div>​
<h1>Hello</h1>​
<p>Hi</p>​
</div>
21

Transformed into:

_jsxs("div", {​
children: [​
_jsx("h1", { children: "Hello" }),​
_jsx("p", { children: "Hi" })​
]​
});

JSX Code​
↓​
Transpiler (Babel / Vite)​
↓​
JavaScript (createElement / jsx-runtime)​
↓​
Virtual DOM (JS Objects)​
↓​
Diffing Algorithm​
↓​
Real DOM (Browser UI)

Why JSX is Needed

Without JSX:

const element = [Link]("h1", null, "Hello World");



With JSX:

const element = <h1>Hello World</h1>;


22

JSX makes code:

●​ Cleaner
●​ Shorter
●​ More readable

Rules of JSX

1. Single Parent Element


return (​
<div>​
<h1>Hello</h1>​
<p>Welcome</p>​
</div>​
);
JSX must return one root element

2. Use className instead of class


<div className="container"></div>
Because class is a reserved keyword in JavaScript

3. JavaScript inside JSX → {}


const name = "Teja";​
return <h1>Hello {name}</h1>;
JSX allows embedding JS expressions

4. Self-closing Tags
<img src="[Link]" />

5. Use camelCase for attributes


23

<button onClick={handleClick}></button>

Embedding Expressions in JSX

JSX allows dynamic content:

const num = 10;​



return <h1>{num * 2}</h1>;
Output: 20

—-------------------------------------------------------------

4.5 React Components


A component is a reusable, independent piece of UI.

Syntax:
function ComponentName() {​
return (​
<JSX />​
);​
}

Component Execution Flow

When React renders:

Step-by-step:

1.​ Call component function


2.​ Generate JSX
3.​ Convert JSX → Virtual DOM
4.​ Compare with previous DOM (Reconciliation)
5.​ Update real DOM (Rendering)
24

Types of Components
There are two primary types of React components:

1. Class Components

2. Functional Components (After React 16.8)

1.​ Class Components (old version)


A class component is a JavaScript class that extends [Link] and returns
UI using a render() method.

When creating a React component, the component's name must start with an upper
case letter.

class Car extends [Link] {

render() {

return <h2>Hi, I am a Car!</h2>;

Now your React application has a component called Car, which returns a <h2> element.

To use this component in your application, use similar syntax as normal HTML: <Car />

Display the Car component in the "root" element: [Link]


import React from 'react';​
import { createRoot } from 'react-dom/client'​

25

class Car extends [Link] {​


render() {​
return <h2>Hi, I am a Car!</h2>;​
}​
}​

createRoot([Link]('root')).render(​
<Car />​
);

Constructor in Class Components

Purpose
●​ Initialize state
●​ Setup initial values

If there is a constructor() function in your component, this function will be called


when the component gets initiated.

The constructor function is where you initiate the component's properties.


constructor() {​
super();​
[Link] = { color: "red" };​
}

super() → calls parent constructor

Required to access:

●​ [Link]
●​ [Link]

Example of Prop
Props are like function arguments, and you send them into the component as attributes.
26

Use an attribute to pass a color to the Car component, and use it in the render
function:

import React from 'react';​


import { createRoot } from 'react-dom/client'​

class Car extends [Link] {​
render() {​
return <h2>I am a {[Link]} Car!</h2>;​
}​
}​

createRoot([Link]('root')).render(​
<Car color="red"/>​
);

Props in the Constructor


If your component has a constructor function, the props should always be passed to the
constructor and also to the [Link] via the super() method.

import React from 'react';​


import { createRoot } from 'react-dom/client'​

class Car extends [Link] {​
constructor(props) {​
super(props);​
}​
render() {​
return <h2>I am a {[Link]}!</h2>;​
}​
}​

createRoot([Link]('root')).render(​
<Car model="BMW X5"/>​
);
27

Example of State
Create a constructor function in the Car component, and add a color property:
import React from 'react';​
import { createRoot } from 'react-dom/client'​

class Car extends [Link] {​
constructor() {​
super();​
[Link] = {color: "red"};​
}​
render() {​
return <h2>I am a {[Link]} Car!</h2>;​
}​
}​

createRoot([Link]('root')).render(​
<Car />​
);

—-----------------------------------

class Car extends [Link] {


constructor(props) {
super(props);
[Link] = { color: "red" };
}

changeColor = () => {
[Link]({ color: "blue", model:"BMW" });
};

render() {
return (
<div>
<h2 style={{ color: [Link] }}>
I am a {[Link]} Car!
</h2>
28

<button onClick={[Link]}>Change Color</button>


</div>
);
}
}
—--------------------------------------------------

Combination of prop and state in the Constructor

import React from 'react';​


import { createRoot } from 'react-dom/client'​

class Car extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {color: "red"};​
}​
render() {​
return <h2>I am a {[Link]}!</h2>​
<h3>I am a {[Link]} Car!</h3>​

}​
}​

createRoot([Link]('root')).render(​
<Car model="BMW X5"/>​
);

Feature Props (Properties) State

Who owns it? Owned by parent component Owned and managed by the
component itself
29

Can it change? Immutable (read-only) for the Mutable (can be changed)


component

How to change? Cannot change inside the Use [Link]()


component

Purpose Pass data from parent to child Manage internal data that can
change over time

Re-rendering Changes when parent re-renders Changes when setState() is


and passes new props called

Like Function parameters Local variables that can change

Components in Components

We can refer to components inside other components:

import React from 'react';​


import { createRoot } from 'react-dom/client'​

class Car extends [Link] {​
render() {​
return <h2>I am a Car!</h2>;​
}​
}​

class Garage extends [Link] {​
render() {​
return (​
<div>​
<h1>Who lives in my Garage?</h1>​
<Car />​
</div>​
30

);​
}​
}​

createRoot([Link]('root')).render(​
<Garage />​
);

Before React 16.8, Class components were the only way to track state and lifecycle on
a React component. Function components were considered "state-less".

2. Functional Components
Functional components are JavaScript functions that return React elements
and are the preferred way to build modern React applications.

Basic Functional Component

function App() {​
return <h1>Hello World</h1>;​
}

But internally, React treats it like:

const element = App();


This returns a React Element Object

{​
type: 'h1',​
props: { children: 'Hello World' }​
}

●​ Can manage state and lifecycle logic using React Hooks.


●​ Use a simpler syntax, making them ideal for reusable components.
31

●​ Offer better performance by avoiding the use of the this keyword.

Component-Based Architecture and Composition in React

In React, a component-based architecture allows you to build complex user interfaces


by composing smaller, reusable, and independent pieces called components. A parent
component like a Header acts as a container that organizes multiple child components
such as Logo, CompanyName, Menu, and Contact, forming a clear hierarchical
structure. This approach helps in breaking down the UI into manageable parts, making
development more structured and easier to understand.

Each child component is designed to be self-contained, meaning it encapsulates its own


structure, logic, and styling. Because of this independence, components can be reused
across different parts of the application without duplication. For example, a Menu
component can be used in both Header and Footer, while still maintaining its own
functionality, which improves consistency and reduces development effort.

These components also work together cohesively through React’s unidirectional data
flow, where data is passed from parent to child using props. This ensures better control
over data and makes debugging and maintenance easier, as changes in one component
do not unnecessarily affect others. Overall, this modular design promotes scalability,
maintainability, and clean separation of concerns, enabling developers to build efficient
and well-organized applications.
32

ReactJS and React Native are both popular JavaScript libraries used for
building user interfaces. While they share similar concepts, they are used
for different platforms and purposes.

●​ ReactJS is mainly used for building web applications and runs in


the browser.
●​ React Native is used for developing mobile applications for
Android and iOS.
●​ React Native uses native components instead of HTML and CSS
like ReactJS.
33

4.6 *React component lifecycle


Everything in this world follows a cycle, whether it’s plants, animals, or humans. They
are born, they grow and they die, thus following a cycle. React components also follow a
cycle. They are created (mounted), they are grown(updated), and they die
(unmounting).This is nothing but called a component lifecycle.

A React component has three different phases in its lifecycle, including mounting,
updating, and unmounting. Each phase has its own methods which are responsible for
a particular stage in a component’s lifecycle.
34

3 Main Phases of Lifecycle

1.​Mounting Phase (Component Creation)

Mounting means inserting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a
component:

1.​ constructor()
2.​ getDerivedStateFromProps()
3.​ render()
4.​ componentDidMount()

The render() method is required and will always be called, the others are optional and
will be called if you define them.
35

1.​ 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.

The constructor() method is called with the props, as arguments, and you should
always start by calling the super(props) before anything else, this will initiate the
parent's constructor method and allow the component to inherit methods from its parent
([Link]).

Example:

The constructor() method is called, by React, every time you make a component:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
render() {​
return (​
<h1>My Favorite Color is {[Link]}</h1>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
)

Run Example

2.​ getDerivedStateFromProps()
36

The getDerivedStateFromProps() method is called right before rendering the


element(s) in the DOM.

This is the natural place to set the state object based on the initial props.

It takes state as an argument, and returns an object with changes to the state.

The example below starts with the favorite color being "red", but the
getDerivedStateFromProps() method updates the favorite color based on the
favcol attribute:

Example: The getDerivedStateFromProps() method is called right before the render


method:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
static getDerivedStateFromProps(props, state) {​
return {favoritecolor: [Link] };​
}​
render() {​
return (​
<h1>My Favorite Color is {[Link]}</h1>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header favcol="yellow"/>​
);

Run Example

3.​ render()
37

The render() method is required, and is the method that actually outputs the HTML to
the DOM.

Example: A simple component with a simple render() method:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
render() {​
return (​
<h1>This is the content of the Header component</h1>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
);

Run Example

4.​ componentDidMount()

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in
the DOM.

Example: At first my favorite color is red, but give me a 5 second, and it is yellow
instead:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
38

componentDidMount() {​
setTimeout(() => {​
[Link]({favoritecolor: "yellow"})​
}, 5000)​
}​
render() {​
return (​
<h1>My Favorite Color is {[Link]}</h1>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
);

Run Example

—--------------------------------------------------------------------------------------------------------------------------------

2. Updating Phase (Re-rendering)


The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or


props.

React has five built-in methods that gets called, in this order, when a component is
updated:

1.​ getDerivedStateFromProps()
2.​ shouldComponentUpdate()
3.​ render()
4.​ getSnapshotBeforeUpdate()
5.​ componentDidUpdate()
39

The render() method is required and will always be called, the others are optional and
will be called if you define them.

1.​ getDerivedStateFromProps

Also at updates the getDerivedStateFromProps method is called. This is the first


method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial props.

The example below has a button that changes the favorite color to blue, but since the
getDerivedStateFromProps() method is called, which updates the state with the
color from the favcol attribute, the favorite color is still rendered as yellow:

Example:
If the component gets updated, the getDerivedStateFromProps() method is called:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
static getDerivedStateFromProps(props, state) {​
return {favoritecolor: [Link] };​
}​
changeColor = () => {​
[Link]({favoritecolor: "blue"});​
}​
render() {​
return (​
<div>​
<h1>My Favorite Color is {[Link]}</h1>​
<button type="button" onClick={[Link]}>Change
color</button>​
40

</div>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header favcol="yellow" />​
);​

/*​
This example has a button that changes the favorite color to blue,​
but since the getDerivedStateFromProps() method is called,​
the favorite color is still rendered as yellow​
(because the method updates the state​
with the color from the favcol attribute).​
*/

Run Example

[Link]

In the shouldComponentUpdate() method you can return a Boolean value that


specifies whether React should continue with the rendering or not.

The default value is true.

The example below shows what happens when the shouldComponentUpdate()


method returns false:

Example:
Stop the component from rendering at any update:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
41

super(props);​
[Link] = {favoritecolor: "red"};​
}​
shouldComponentUpdate() {​
return false;​
/* return true; */​
}​
changeColor = () => {​
[Link]({favoritecolor: "blue"});​
}​
render() {​
return (​
<div>​
<h1>My Favorite Color is {[Link]}</h1>​
<button type="button" onClick={[Link]}>Change
color</button>​
</div>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
);​


/*​
This example has a button that changes the favorite color to blue,​
but since the shouldComponentUpdate() method is called,​
the favorite color is still rendered as red​
(because the method returns false).​
*/

Run Example

3. render()
42

The render() method is of course called when a component gets updated, it has to
re-render the HTML to the DOM, with the new changes.

The example below has a button that changes the favorite color to blue:

Example:
Click the button to make a change in the component's state:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
changeColor = () => {​
[Link]({favoritecolor: "blue"});​
}​
render() {​
return (​
<div>​
<h1>My Favorite Color is {[Link]}</h1>​
<button type="button" onClick={[Link]}>Change
color</button>​
</div>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
);

Run Example
43

4. getSnapshotBeforeUpdate

In the getSnapshotBeforeUpdate() method you have access to the props and state
before the update, meaning that even after the update, you can check what the values
were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also include the


componentDidUpdate() method, otherwise you will get an error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and after one
second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has a
getSnapshotBeforeUpdate() method, this method is executed, and writes a message
to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in the


empty DIV2 element:

Example:
Use the getSnapshotBeforeUpdate() method to find out what the state object
looked like before the update:

import { createRoot } from 'react-dom/client'​


import React from 'react';​

class Header extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
componentDidMount() {​
44

setTimeout(() => {​
[Link]({favoritecolor: "yellow"})​
}, 1000)​
}​
getSnapshotBeforeUpdate(prevProps, prevState) {​
[Link]("div1").innerHTML =​
"Before the update, the favorite was " + [Link];​
}​
componentDidUpdate() {​
[Link]("div2").innerHTML =​
"The updated favorite is " + [Link];​
}​
render() {​
return (​
<div>​
<h1>My Favorite Color is {[Link]}</h1>​
<div id="div1"></div>​
<div id="div2"></div>​
</div>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
);

Run Example

5. componentDidUpdate

The componentDidUpdate method is called after the component is updated in the


DOM.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".
45

When the component has been mounted, a timer changes the state, and the color
becomes "yellow".

This action triggers the update phase, and since this component has a
componentDidUpdate method, this method is executed and writes a message in the
empty DIV element:

Example:
The componentDidUpdate method is called after the update has been rendered in the
DOM:

class Header extends [Link] {​


constructor(props) {​
super(props);​
[Link] = {favoritecolor: "red"};​
}​
componentDidMount() {​
setTimeout(() => {​
[Link]({favoritecolor: "yellow"})​
}, 1000)​
}​
componentDidUpdate() {​
[Link]("mydiv").innerHTML =​
"The updated favorite is " + [Link];​
}​
render() {​
return (​
<div>​
<h1>My Favorite Color is {[Link]}</h1>​
<div id="mydiv"></div>​
</div>​
);​
}​
}​

createRoot([Link]('root')).render(​
<Header />​
46

);

Run Example

—----------------------------------------------------------------------------------------------------------------------------

3. Unmounting
The next phase in the lifecycle is when a component is removed from the DOM, or
unmounting as React likes to call it.

React has only one built-in method that gets called when a component is unmounted:

●​ componentWillUnmount()

componentWillUnmount

The componentWillUnmount method is called when the component is about to be


removed from the DOM.

Example: Click the button to delete the header:

import React from 'react';​


import ReactDOM from 'react-dom/client';​

class Container extends [Link] {​
constructor(props) {​
super(props);​
[Link] = {show: true};​
}​
delHeader = () => {​
[Link]({show: false});​
}​
render() {​
let myheader;​
if ([Link]) {​
myheader = <Child />;​
47

};​
return (​
<div>​
{myheader}​
<button type="button" onClick={[Link]}>Delete
Header</button>​
</div>​
);​
}​
}​
class Child extends [Link] {​
componentWillUnmount() {​
alert("The component named Header is about to be unmounted.");​
}​
render() {​
return (​
<h1>Hello World!</h1>​
);​
}​
}​
const root = [Link]([Link]('root'));​
[Link](<Container />);

Run Example
48

4.7 Handling Events


Handling events in [Link] is similar to handling events on DOM elements. React has
the same events as HTML.

React uses the camelCase convention for event names, which differs from the standard
HTML event names (e.g., onClick instead of onclick).

1. Adding Event Handlers

Example: HTML + JavaScript Version (DOM Events)

<html>​
<body>​
<button id="btn">Click Me</button>​
<p id="count">Count: 0</p>​

<script>​
let count = 0;​
49


const button = [Link]("btn");​
const display = [Link]("count");​

// function (event handler)​
function handleClick() {​
count++;​
[Link] = "Count: " + count;​
}​
// Attach function to event​
[Link]("click", handleClick);​
</script>​

</body>​
</html>

You control everything step-by-step (imperative)

●​ We store count in a variable


●​ Manually select elements (getElementById)
●​ Attach event using addEventListener
●​ Manually update UI (textContent)

React Version (Same Example):

In React, event handlers are added directly to elements via JSX attributes.
import { useState } from "react";​

function App() {​
const [count, setCount] = useState(0);​

const handleClick = () => {​
setCount(count + 1);
//setCount(prev => prev + 1);
//This ensures correct updates when multiple clicks happen fast.​
};​

return (​
<div>​
50

<button onClick={handleClick}>​
Click Me​
</button>​

<p>Count: {count}</p>​
</div>​
);​
}​

export default App;

React handles UI updates (declarative approach)

●​ useState stores count


●​ No DOM selection
●​ onClick handles event
●​ UI updates automatically when state changes

Difference between HTML(DOM) events and React Events from example

Feature JavaScript React

State storage Variable (count) useState

DOM access Manual Automatic

UI update Manual Auto re-render


(textContent)

Event binding addEventListener onClick

2. Reading Props in Event Handlers

It means:

●​ A parent component sends data (props)


●​ The child component uses that data inside an event handler
51

Step 1: Parent Component

<App step={2}/>

Step 2: Child Component (Reading Props in Event)

import React from 'react';​


import { useState } from 'react'​

function App(props) {​
const [count, setCount] = useState(0);​

const handleClick = () => {​
// reading prop inside event handler​
setCount(prev => prev + [Link]);​
};​

return (​
<div>​
<button onClick={handleClick}>​
Increase by {[Link]}​
</button>​
<p>Count: {count}</p>​
</div>​
);​
}​

export default App
●​ Parent sends step = 2
●​ Button clicked
●​ handleClick() runs
●​ Reads [Link]
●​ Count increases by 2

3. Passing Event Handlers as Props


Passing event handlers as props (Parent → Child communication)

●​ Instead of writing the click logic inside the child,


●​ The parent sends a function (event handler) as a prop,
52

●​ The child calls that function on click.

Step 1: [Link]
import { StrictMode } from 'react'​
import { createRoot } from 'react-dom/client'​
import App from './[Link]'​
import Counter from './example/[Link]'​

// Rendering a Component​
createRoot([Link]('root')).render(​
<StrictMode>​
<App step={2} />​
</StrictMode>,​
)

Step2: [Link] (Parent)

import { useState } from 'react'​


import Counter from './example/[Link]'​

function App({ step }) {​
const [count, setCount] = useState(0);​

// handler defined in parent​
const handleIncrement = () => {​
setCount(prev => prev + step);​
};​

return (​
<div>​
<p>Count: {count}</p>​

{/* passing handler */}​
<Counter onIncrement={handleIncrement} step={step} />​
</div>​
);​
}​

export default App
53

Step 3: [Link] (child)


function Counter({ onIncrement }) {​
return (​
<button onClick={() => onIncrement(2)}>​
Increase by 2​
</button>​
);​
}​
export default Counter;

●​ Button clicked in child (Child sends 2)


●​ onIncrement() runs
●​ Function actually belongs to parent (Parent receives 2)
●​ Parent state updates (State updates by 2)
●​ UI re-renders

4.8 Conditional Rendering


Conditional rendering means: Showing different UI (components/elements)
based on a condition.

Instead of always displaying the same UI, React decides what to render
depending on state/props.

React does NOT manually show/hide elements like traditional JS (display:


none).

Instead: React decides what to return (render)

Example: return condition ? <A /> : <B />;

So:

●​ UI = function of state
●​ Change state → React re-renders → UI changes automatically

This helps keep the interface relevant and responsive to changes.


54

●​ Displays different UI elements based on the current state or props.


●​ Automatically updates what the user sees when data or conditions
change.
●​ Removes the need to manually manipulate the DOM to show or
hide content.

Different Methods:

1. Using If/Else Statements: If/else statements allow rendering different


components based on conditions. This approach is useful for complex
conditions.

function App() {​
const [isLoggedIn, setIsLoggedIn] = useState(false);​

if (isLoggedIn) {​
return (​
<div>​
<h1>Welcome User</h1>​
<button onClick={() => setIsLoggedIn(false)}>Logout</button>​
</div>​
);​
}​

return (​
55

<div>​
<h1>Please Login</h1>​
<button onClick={() => setIsLoggedIn(true)}>Login</button>​
</div>​
);​
}
●​ Entire UI changes based on condition
●​ Only ONE return executes

2. Using Ternary Operator

The ternary operator (condition ? expr1: expr2) is a concise way to


conditionally render JSX elements. It’s often used when the logic is simple
and there are only two options to render.

function App() {​
const [isLoggedIn, setIsLoggedIn] = useState(false);​

return (​
<div>​
<h1>{isLoggedIn ? "Welcome User" : "Please Login"}</h1>​

<button onClick={() => setIsLoggedIn(!isLoggedIn)}>​
{isLoggedIn ? "Logout" : "Login"}​
</button>​
</div>​
);​
56

●​ Best for two conditions

●​ Clean and readable

3. Using Logical AND (&&) Operator

The && operator returns the second operand if the first is true, and nothing if
the first is false. This can be useful when you only want to render something
when a condition is true.

function App() {​
const [notifications, setNotifications] = useState(3);​

return (​
<div>​
<h1>Dashboard</h1>​

{notifications > 0 && (​
<p>You have {notifications} new notifications</p>​
)}​

<button onClick={() => setNotifications(0)}>​
Clear Notifications​
</button>​
</div>​
57

);​
}
●​ No “else”
●​ Only renders when condition is true

4. Using Switch Case Statements

Switch case statements are useful when you need to handle multiple
conditions, which would otherwise require multiple if conditions. This
approach can be more readable if there are many conditions to check.

function App() {​
const [status, setStatus] = useState("loading");​

const renderContent = () => {​
switch (status) {​
case "loading":​
return <p>Loading...</p>;​
case "success":​
return <p>Data Loaded Successfully</p>;​
case "error":​
return <p>Error occurred</p>;​
default:​
58

return null;​
}​
};​

return (​
<div>​
<h1>Status</h1>​
{renderContent()}​

<button onClick={() => setStatus("success")}>Success</button>​
<button onClick={() => setStatus("error")}>Error</button>​
</div>​
);​
}
●​ Best for multiple cases
●​ Cleaner than many if-else

5. CONDITIONAL LIST RENDERING

function App() {​
const items = ["apple", "banana", "grape", "kiwi"];​

return (​
<div>​
<h1>Fruits with letter 'a'</h1>​

{[Link]((item, index) =>​
[Link]("a") ? <p key={index}>{item}</p> : null​
)}​
</div>​
);​
}

User Action → State Changes → React Re-renders → UI Updates


59

4.9 Lists and Keys


What are Lists in React?
A list simply means rendering multiple similar elements dynamically using data.

Cars= ['Ford', 'BMW', 'Audi']

Instead of writing HTML manually like this:


<li>Ford</li>​
<li>BMW</li>​
<li>Audi</li>

Using JavaScript (Dynamic Way)


<ul id="carList"></ul>​
<script>​
const cars = ['Ford', 'BMW', 'Audi'];​

const list = [Link]("carList");​

[Link](car => {​
const li = [Link]("li");​
[Link] = car;​
[Link](li);​
});​
</script>

React encourages using JavaScript arrays and generating UI using .map() method.

.map() is a JavaScript array method used to: Transform each element of an array into
a new value

●​ It loops through the array


●​ Applies a function to each element
●​ Returns a new array
60

There are two common ways to use .map()—with an implicit return and with an
explicit return.

Syntax: Implicit return


[Link]( ( ) => (​

))

Example:

function CarsList() {​
const cars = ['Ford', 'BMW', 'Audi'];​
return (​
<ul>​
{​
[Link]((car) => (​
<li>{car}</li>​
))​
}​
</ul>​
);​
}

Syntax: Explicit return


[Link]( ( ) => {​
return​
})

Example

function CarsList() {​
const cars = ['Ford', 'BMW', 'Audi'];​
return (​
<ul>​
{[Link]((car) => {​
return <li>{car}</li>;​
})}​
</ul>​
);​
61

If you run the above code, React will show a warning:

“Each child in a list should have a unique key prop”

Why?

Because React needs a way to identify each item uniquely when updating the UI.

Fixing the Warning with Keys

What are Keys in React?

A key is a special attribute that helps React:

●​ Track elements efficiently


●​ Identify which items changed, added, or removed
●​ Improve performance during re-rendering

Example:
function CarsList() {​
const cars = ['Ford', 'BMW', 'Audi'];​

return (​
<ul>​
{[Link]((car, index) => {​
return <li key={index}>{car}</li>​
})}​
</ul>​
);​
}
62

React uses a concept called Virtual DOM.

When data changes:

1.​ React compares old UI and new UI


2.​ It updates only what changed

Keys allow React to keep track of elements. This way, if an item is updated or removed,
only that item will be re-rendered instead of the entire list.

Imagine this list: cars = ['Ford', 'BMW', 'Audi'];​


Now updated to: ['BMW', 'Audi', 'Honda'];​

If no keys:

●​ React gets confused

●​ May re-render everything

With keys:

●​ "BMW" and "Audi" are reused

●​ Only "Ford" removed, "Honda" added

Best Practices for Keys

1.​ Use Unique IDs (Best Method)


function CarsList() {​
const cars = [​
{ id: 1, name: "BMW", price: 8000000 },​
{ id: 2, name: "Audi", price: 7000000 },​
{ id: 3, name: "Tesla", price: 9000000 }​
];​

return (​
<ul>​
{[Link]((car) => (​
<li key={[Link]}>​
63

{[Link]} - ₹{[Link]}​
</li>​
))}​
</ul>​
);​
}

2.​ Using Array Index as Key (Only if necessary)


<li key={index}>{car}</li>
Use this only when:

●​ List is static (no add/remove/reorder)

Avoid Random Keys: <li key={[Link]()}>{car}</li>

Bad practice because:

●​ Keys change every render


●​ React re-renders everything

4.10 Forms
React forms are all about handling user input (text fields, checkboxes, selects, etc.)
and managing that data inside your component state. If you understand forms well, you
can build login pages, search bars, registration systems, and more.

What is a Form in React?

A form in React works similarly to HTML forms, but with extra control using state.

In plain HTML:

●​ The DOM handles form data

In React:

●​ But data is handled by React components (state), not DOM.

●​ State is a variable that stores data and can change over time, and when it
changes, React automatically updates the UI.
64

Basic Form in React

Just like in HTML, React uses forms to allow users to interact with the web page.

function MyForm() {​
return (​
<form>​
<p>Enter your name:</p>​
<input type="text" />​
</form>​
);​
}
●​ This works like normal HTML
●​ But React does not control it yet

Handling Forms

In React, form data is stored in state

Controlled Components:

A controlled component is a form element whose value is controlled by React state.

function MyForm() {​
const [name, setName] = useState("");​

return (​
<form>​
<p>Enter your name:</p>​
<input​
type="text"​
onChange={(e) => setName([Link])}​
/>​
<br/> you typed: <h2>{name}</h2>​
</form>​
);​
}
65

const [name, setName] = useState("");

name → Current State Value - This stores data

setName → Function to Update State - This updates the value.

useState("") → Initial Value - Starting value is empty string

How it works:

User types "Teja" -> onChange fires -> setName("Teja") -> React updates UI ->I/P shows "Teja"

Flow:

User types → onChange → state updates → UI updates

Handling Form Submission

function MyForm() {​
const [name, setName] = useState("");​
const [submittedName, setSubmittedName] = useState(""); ​

const handleSubmit = (e) => {​
//[Link]();​
setSubmittedName(name);​
};​

return (​
<>​
<form onSubmit={handleSubmit}>​
<input onChange={(e) => setName([Link])} />​
<input type="submit" />​
</form>​
You submitted: <h2> {submittedName}</h2>​
</>​
);​
}​
66

React prevents page reload using [Link]().

Multiple Inputs

function CricketForm() {​
const [formData, setFormData] = useState({​
player: "",​
runs: "",​
team: ""​
});​

const [submittedData, setSubmittedData] = useState(null);​

// Handle all inputs​
const handleChange = (e) => {​
const { name, value } = [Link];​

setFormData({​
...formData, //Copy everything → Update only changed field → Keep rest
same​
[name]: value​
});​
};​

// Handle submit​
const handleSubmit = (e) => {​
[Link]();​
setSubmittedData(formData);​
};​

return (​
<>​
<h2>Cricket Player Form</h2>​

<form onSubmit={handleSubmit}>​
<input​
type="text"​
name="player"​
placeholder="Player Name"​
value={[Link]}​
onChange={handleChange}​
/> <span style={{ padding: "1px" }}></span>​
67


<input​
type="number"​
name="runs"​
placeholder="Runs"​
value={[Link]}​
onChange={handleChange}​
/><span style={{ padding: "2px" }}></span>​

<input​
type="text"​
name="team"​
placeholder="Team"​
value={[Link]}​
onChange={handleChange}​
/><span style={{ padding: "2px" }}></span>​

<button type="submit">Submit</button>​
</form>​

{submittedData && (​
<div>​
<h3>Submitted Data:</h3>​
<p>Player: {[Link]}</p>​
<p>Runs: {[Link]}</p>​
<p>Team: {[Link]}</p>​
</div>​
)}​
</>​
);​
}

State Lifting?
State Lifting means moving state from a child component to a common parent so
multiple components can share it.

●​ Form → enters player data


●​ Scoreboard → displays player data

If both need the same data → you keep it in a central scoreboard system (parent)
68

Currently your code is like this:

CricketForm()

└── handles input + display

Everything in one component → works, but not scalable

So Now Split into:

App (Parent)

├── CricketForm (Child 1 - Input)

└── ScoreBoard (Child 2 - Display)


69

[Link] (Parent)
import CricketForm from './demo/CricketForm'​
import ScoreBoard from './demo/ScoreBoard'​

function App() {​
const [submittedData, setSubmittedData] = useState(null);​

return (​
<>​
<h2>Cricket Player Form</h2>​

<CricketForm setSubmittedData={setSubmittedData} />​
<ScoreBoard submittedData={submittedData} />​
</>​
);​
}​

export default App

●​ State is now in App (parent)


●​ Shared with both children

[Link] (child 1 - Generated Data)


import { useState } from "react";​

function CricketForm({ setSubmittedData }) {​
const [formData, setFormData] = useState({​
player: "",​
runs: "",​
team: ""​
});​

const handleChange = (e) => {​
const { name, value } = [Link];​

setFormData({​
...formData,​
[name]: value​
});​
};​

const handleSubmit = (e) => {​
[Link]();​
setSubmittedData(formData); // send data to parent​
70

};​

return (​
<form onSubmit={handleSubmit}>​
<input​
type="text"​
name="player"​
placeholder="Player Name"​
value={[Link]}​
onChange={handleChange}​
/> <span style={{ padding: "1px" }}></span>​

<input​
type="number"​
name="runs"​
placeholder="Runs"​
value={[Link]}​
onChange={handleChange}​
/><span style={{ padding: "2px" }}></span>​

<input​
type="text"​
name="team"​
placeholder="Team"​
value={[Link]}​
onChange={handleChange}​
/><span style={{ padding: "2px" }}></span>​

<button type="submit">Submit</button>​

</form>​
);​
}​

export default CricketForm;

●​ Child does NOT store final data


●​ It sends data to parent
71

[Link] (child 2: Received Data from parent)

function ScoreBoard({ submittedData }) {​


return (​
<>​
{submittedData && (​
<div>​
<h3>Scoreboard</h3>​
<p>Player: {[Link]}</p>​
<p>Runs: {[Link]}</p>​
<p>Hello Team: {[Link]}</p>​
</div>​
)}​
</>​
);​
}​

export default ScoreBoard;

Receives data from parent via props

Why State Lifting?

Benefits
●​ Share data between components
●​ Centralized control
●​ Cleaner architecture
●​ Scalable apps

Without it
●​ Components isolated
●​ Data duplication
●​ Hard to manage
72

You might also like