0% found this document useful (0 votes)
36 views31 pages

Unit-2 Fullstack Amt

This document provides an overview of React, a JavaScript library for building user interfaces, covering its core concepts, including components, JSX, props, state, and lifecycle methods. It also explains setting up a React project using Create React App, the Virtual DOM's role in optimizing UI updates, and the differences between React elements and components. Additionally, it discusses methods for dynamically constructing elements with data and the types of components in React.

Uploaded by

ayush05deo
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)
36 views31 pages

Unit-2 Fullstack Amt

This document provides an overview of React, a JavaScript library for building user interfaces, covering its core concepts, including components, JSX, props, state, and lifecycle methods. It also explains setting up a React project using Create React App, the Virtual DOM's role in optimizing UI updates, and the differences between React elements and components. Additionally, it discusses methods for dynamically constructing elements with data and the types of components in React.

Uploaded by

ayush05deo
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
You are on page 1/ 31

UNIT-2 FULL STACK AMT

1. Introduction to React and Its Core Concepts

What is React?
React is a JavaScript library for building user interfaces (UI), especially
single-page applications (SPAs), where the content dynamically updates
without reloading the whole page.
• Developed by Facebook (now Meta)
• First released in 2013
• Focuses on the View layer (V) in the MVC architecture
• Enables reusable components and efficient DOM updates

Why Use React?


• Fast and responsive UI through virtual DOM
• Component-based architecture for modular code
• Easy to manage state and props
• Rich ecosystem with support for routing, state management, and backend
integration
• Strong community and job demand

Core Concepts of React:


1. Components
• Building blocks of any React application.
• Can be functional or class-based
• Help split the UI into independent, reusable pieces.
Example (Functional Component):
function Welcome() {
return <h1>Hello, React!</h1>;
}

2. JSX (JavaScript XML)


• A syntax extension for JavaScript.
• Looks like HTML but works inside JavaScript code.
• JSX is transpiled into React.createElement() by Babel.
Example:
const element = <h1>Welcome to React</h1>;

3. Props (Properties)
• Read-only inputs to a component
• Used to pass data from parent to child components
Example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Usage:
<Welcome name="Aditya" />

4. State
• A data container that changes over time and affects the component’s
behavior.
• Managed within a component (especially in class components or using
useState in functional components)
Example:
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

5. Lifecycle Methods (for Class Components)


• Allow code to run at specific times in a component’s life (mounting,
updating, unmounting).
Common Methods:
• componentDidMount()
• componentDidUpdate()
• componentWillUnmount()
In functional components, React Hooks like useEffect() handle similar
behavior.

6. Hooks (Functional Components)


Hooks are functions that let you use state and other features in functional
components.
• useState() – to manage local state
• useEffect() – to perform side effects (e.g., API calls)
• useContext(), useRef(), useReducer(), etc.
Example (useEffect):
useEffect(() => {
console.log("Component rendered!");
}, []);

7. Virtual DOM
• A lightweight copy of the real DOM maintained by React.
• React uses it to detect changes and update only necessary parts of the
real DOM.
• This results in faster and efficient UI updates.

8. One-Way Data Binding


• Data flows from parent to child using props.
• Makes the code more predictable and easier to debug.

9. React Router
• Used for handling navigation and routing in single-page applications
(SPAs).
• Enables URL-based navigation without reloading the page.
Example:
<Route path="/home" element={<Home />} />

10. State Management


For managing app-wide data or global states:
• Context API – Built-in method to share state across components
• Redux, Zustand, Recoil – Advanced state management libraries
Summary Table:

2. Setting Up a React Project with Create React App:


What is Create React App (CRA)?
Create React App is a command-line tool provided by the React team that sets
up a modern React project with a ready-to-use build configuration, so you
don’t need to manually configure tools like Webpack, Babel, etc.
• Ideal for beginners and intermediate developers
• Provides a default project structure
• Supports hot reloading, ES6+, JSX, linting, and more

Prerequisites:
Before you can use CRA, make sure you have the following installed:
• Node.js (v14 or higher)
• npm (Node Package Manager) or yarn
To verify:
node -v
npm -v

Steps to Set Up a React Project Using Create React App:


Step 1: Install Create React App (optional global install)
npm install -g create-react-app
Alternatively, use npx which doesn't require global installation.

Step 2: Create a New React Project


npx create-react-app my-app
• my-app is the folder name for your new project.
• This will create a new folder and download all necessary dependencies.

Step 3: Navigate into Your Project Directory


cd my-app

Step 4: Start the Development Server


npm start
• Opens the app in your default browser at http://localhost:3000/
• Includes live reloading, so changes reflect instantly

Available Commands in CRA Projects

Note: npm run eject is irreversible and reveals configuration files (only use if
customization is needed).
First Edits (Try This After Setup)
Edit src/App.js to modify the content:
function App() {
return (
<div>
<h1>Hello, React!</h1>
</div>
);
}

export default App;


Changes will auto-refresh in the browser.

Next Steps After Setup


• Add components in the src/ folder
• Create reusable modules
• Use React Router for navigation
• Connect to APIs using fetch or axios
• Learn about useState, useEffect, and props

3. Virtual DOM in React:


What is the Virtual DOM?
The Virtual DOM (VDOM) is an in-memory (virtual) representation of the Real
DOM (Document Object Model). It is a lightweight copy of the actual browser
DOM used by React to optimize UI updates.
• React uses the Virtual DOM to efficiently render updates without
directly touching the real DOM unless necessary.
• It improves performance, speed, and user experience in modern web
applications.

Why Virtual DOM?


Updating the real DOM is slow and expensive because:
• It involves layout recalculations, re-painting, and reflows.
• Frequent direct DOM manipulation (like in jQuery) can slow down
applications.
The Virtual DOM helps solve this by:
• Minimizing the number of changes made to the actual DOM.
• Batching and optimizing updates to improve performance.

How the Virtual DOM Works in React:


1. Initial Render:
o React creates a Virtual DOM from JSX.
o This Virtual DOM is then used to build the real DOM for the first
time.
2. State or Prop Change:
o When data (state or props) changes, React creates a new Virtual
DOM tree.
3. Diffing Algorithm:
o React compares the new Virtual DOM with the previous Virtual
DOM.
o It finds the differences using a process called “diffing.”
4. Reconciliation:
o React determines the minimal set of changes needed to update the
real DOM.
o Only the parts that changed are updated.
5. DOM Update:
o The real DOM is updated selectively, not completely re-rendered.

Diagram Overview (Conceptual)

Example:
Component before update:
<h1>Hello, Aditya!</h1>
Component after state changes:
<h1>Hello, Riya!</h1>
• React does not replace the entire <h1>.
• It compares the old and new Virtual DOM and sees that only the text
node changed.
• It updates just the text, not the whole element.

Benefits of Using Virtual DOM:


Key Terms:
• Diffing: Comparing two Virtual DOM trees to detect changes.
• Reconciliation: The process of updating the Real DOM based on
differences.

Summary:
• The Virtual DOM is central to React’s performance optimization.
• It allows for faster and more efficient UI updates.
• React ensures the minimum number of updates are made to the Real
DOM, improving performance.

4. React Element
Definition:
A React Element is the smallest building block in a React application.
It is a plain JavaScript object that describes what you want to see on the screen.
• React Elements are immutable.
• They are lightweight representations of actual DOM elements.
• React uses them to build the Virtual DOM.

Syntax:
You can create a React Element in two main ways:
1. Using JSX:
const element = <h1>Hello, World!</h1>;
This looks like HTML but is actually syntactic sugar for:
2. Using React.createElement():
const element = React.createElement('h1', null, 'Hello, World!');
This returns an object like:
{
type: 'h1',
props: {
children: 'Hello, World!'
}
}

Structure of a React Element:


A React Element is an object with the following properties:
{
type: 'tag or component name',
props: {
attribute1: value1,
attribute2: value2,
...
children: childElements
}
}

Example:
JSX Version:
const greeting = <h1 className="welcome">Hello, Aditya!</h1>;
Equivalent React.createElement Version:
const greeting = React.createElement(
'h1',
{ className: 'welcome' },
'Hello, Aditya!'
);
React Element vs React Component:

Important Notes:
• React Elements are not real DOM elements. They are descriptions of
what the DOM should look like.
• They are used internally by React to create and update the Virtual DOM.
• React updates the actual DOM only when the Virtual DOM changes.

Use Case:
You generally don’t create elements manually with React.createElement() in
real projects.
Instead, you use JSX because it’s cleaner and more readable.

Summary:
• React Element is a JS object that describes a DOM node.
• JSX is used to write React Elements in a readable way.
• React Elements are immutable and form the base of the Virtual DOM.
• They are the output of components and input for rendering.
5. React DOM:
Definition:
React DOM is the package in React responsible for rendering React elements
and components to the actual DOM in a web browser.
• It acts as a bridge between React and the browser's DOM API.
• ReactDOM updates the DOM efficiently using the Virtual DOM.

Key Responsibilities:
• Rendering components/elements to the browser.
• Managing updates and re-renders.
• Handling unmounting of components.
• Using virtual DOM diffing and reconciliation to minimize actual DOM
manipulations.

Importing ReactDOM:
In most React apps (especially those created via Create React App), ReactDOM
is imported like this:
import ReactDOM from 'react-dom/client';
Since React v18, React uses the createRoot API from react-dom/client instead
of the old ReactDOM.render() method.

Basic Usage:
Before React 18:
ReactDOM.render(<App />, document.getElementById('root'));
With React 18 (modern way):
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<App />);
• App is your top-level component.
• 'root' is the ID of the DOM element in index.html where your React app
will mount.

How React DOM Works:


1. ReactDOM receives a React Element or Component.
2. It creates the virtual DOM tree using that element.
3. It compares the virtual DOM with the previous tree.
4. It applies the minimal set of changes to the real DOM.

Important Methods in ReactDOM:

Example Setup (index.js):


import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);

root.render(<App />);
index.html (public folder):
<div id="root"></div>

ReactDOM vs React:

Summary:
• ReactDOM connects React components to the browser DOM.
• It handles initial rendering, updates, and unmounting of components.
• In React 18+, always use createRoot() and root.render() instead of
ReactDOM.render().

6. Constructing Elements with Data in React:


Introduction:
In React, you often need to dynamically generate content using JavaScript
data, such as arrays, objects, or user input.
React allows you to embed variables and expressions directly inside JSX,
making it easy to construct elements based on data.
Ways to Construct Elements with Data:
1. Embedding JavaScript Expressions in JSX
You can use {} to inject any JavaScript expression inside JSX.
Example:
const name = 'Aditya';
const element = <h1>Hello, {name}!</h1>;
Output:
Hello, Aditya!

2. Using Template Literals


React JSX supports JavaScript expressions including template literals for
cleaner string construction.
Example:
const user = {
firstName: 'Aditya',
lastName: 'Tripathi'
};

const element = <h2>Hello, {`${user.firstName} ${user.lastName}`}</h2>;


Output:
Hello, Aditya Tripathi

3. Conditional Rendering with Data


You can use ternary operators, if statements, or logical && operators to
display content conditionally.
Example (ternary operator):
const isLoggedIn = true;
const element = <h3>{isLoggedIn ? 'Welcome back!' : 'Please log in'}</h3>;
4. Looping Through Arrays to Create Lists
You can use Array.map() to create lists of elements dynamically.
Example:
const fruits = ['Apple', 'Banana', 'Cherry'];

const listItems = fruits.map((fruit, index) =>


<li key={index}>{fruit}</li>
);

const element = <ul>{listItems}</ul>;


Output:
• Apple
• Banana
• Cherry
Note: The key prop is required to uniquely identify elements in a list.

5. Using Functions to Create Elements


You can construct elements using custom functions for reusability.
Example:
function formatName(user) {
return `${user.firstName} ${user.lastName}`;
}

const user = { firstName: 'Riya', lastName: 'Sharma' };


const element = <h1>Hello, {formatName(user)}</h1>;
6. Combining JSX and Logic
You can declare variables before JSX and use them to simplify rendering logic.
Example:
let greeting;
const hour = new Date().getHours();

if (hour < 12) {


greeting = "Good Morning!";
} else {
greeting = "Good Evening!";
}

const element = <h1>{greeting}</h1>;

Summary Table:

Best Practices:
• Always provide a unique key prop when rendering lists.
• Keep logic clean and outside JSX if it's complex.
• Avoid mutating data directly in JSX expressions.
7. React Components:
Definition:
A React Component is a reusable, independent piece of UI that can be
combined with other components to build a complete user interface.
• Components in React return JSX, which gets rendered as HTML in the
browser.
• React enforces a component-based architecture to promote modularity
and code reuse.

Types of Components:
React supports two main types of components:

1. Functional Components (Modern Standard)


• Stateless by default (though can use useState for state)
• Defined as JavaScript functions
• Use React Hooks for side effects, state, etc.
• Simpler and cleaner than class components
Syntax:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
Or using arrow functions:
const Welcome = ({ name }) => <h1>Hello, {name}!</h1>;

2. Class Components (Older Style)


• Use ES6 class syntax and extend React.Component
• Can have state and lifecycle methods
• Still supported but generally replaced by functional components
Syntax:
import React, { Component } from 'react';

class Welcome extends Component {


render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}

Component Naming Convention:


• Component names must start with an uppercase letter
• <MyComponent />
• <myComponent /> (will be treated as a native HTML element)

Props in Components:
• Props (short for properties) are passed to components like function
arguments.
• Used to customize or pass data into a component.
Example:
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}

// Usage
<Greeting name="Aditya" />
Returning Multiple Elements:
Components can return multiple elements wrapped in a single parent (usually a
<div> or <> fragment).
Example:
function Info() {
return (
<>
<h2>Title</h2>
<p>Description goes here</p>
</>
);
}

Reusability Example:
function Button(props) {
return <button>{props.label}</button>;
}

// Usage
<Button label="Login" />
<Button label="Signup" />

State in Functional Component (with Hooks):


import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}

Summary Table:

Best Practices:
• Use functional components for all new development.
• Keep components small and focused on a single task.
• Use props to make components reusable and customizable.
• Manage shared state using Context API or state management libraries
(e.g., Redux).
8. DOM Rendering in React:
What is DOM Rendering?
DOM Rendering in React refers to the process of displaying React elements
and components into the browser's actual DOM (Document Object Model).
React uses its Virtual DOM to calculate the changes and updates only the
necessary parts of the Real DOM, which makes the rendering process fast and
efficient.

How Rendering Works in React:


1. React Elements (written in JSX) are created.
2. These elements are passed to ReactDOM (via render() or root.render()).
3. React compares the new Virtual DOM with the previous Virtual DOM.
4. React updates the Real DOM with only the parts that changed.

Rendering an Element (Basic Example):


JSX Code:
const element = <h1>Hello, World!</h1>;
Rendering to DOM (React 18):
import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);
HTML File (index.html):
<body>
<div id="root"></div>
</body>
React mounts the content inside the #root element.
Re-Rendering with State Change:
React re-renders the UI automatically when state or props change.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
Every time the button is clicked:
• The state count changes
• React re-renders the component
• React calculates the diff using Virtual DOM
• Only the text node ({count}) is updated in the Real DOM

ReactDOM vs DOM Manipulation (e.g., JavaScript):


React DOM APIs for Rendering:

When Does React Re-render?


React re-renders when:
• A component’s state or props change
• The parent component re-renders
• A context value used in a component changes

Performance Tip:
Use React.memo, useMemo, or shouldComponentUpdate() to avoid
unnecessary re-renders in large apps.

Summary:
• DOM Rendering is the process of putting React elements into the
browser's DOM.
• React uses Virtual DOM diffing to update the browser efficiently.
• Rendering is automatic whenever props or state change.
• In React 18+, always use createRoot() instead of ReactDOM.render().
9. React with JSX:
What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript used in React.
It allows you to write HTML-like code inside JavaScript, making your UI code
more readable and expressive.
JSX is not valid JavaScript by itself. It is compiled by tools like Babel into
React.createElement() calls.

Why Use JSX in React?


• Improves readability by combining markup and logic in one place.
• Makes it easier to visualize component structure.
• Helps avoid typos and bugs compared to raw createElement() calls.
• Supports dynamic expressions, conditionals, and loops.

JSX Syntax Example:


const element = <h1>Hello, JSX!</h1>;
Compiles to:
const element = React.createElement('h1', null, 'Hello, JSX!');

Embedding Expressions in JSX:


Use {} to insert JavaScript expressions into JSX.
const name = 'Aditya';
const element = <h2>Welcome, {name}!</h2>;
You can also embed:
• Math: {5 + 3}
• Function calls: {formatName(user)}
• Conditionals: {isLoggedIn ? 'Yes' : 'No'}
JSX Must Return One Parent Element:
// Correct
return (
<div>
<h1>Title</h1>
<p>Description</p>
</div>
);

// Or use React Fragment


return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
You cannot return multiple sibling elements without wrapping them.

Using Attributes in JSX:


• Use camelCase for most HTML attributes.
• Use className instead of class.
• Use htmlFor instead of for.
<input type="text" placeholder="Enter name" className="input-box" />
<label htmlFor="username">Username:</label>

Conditional Rendering with JSX:


const isLoggedIn = true;
const element = (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);

Lists with JSX:


const fruits = [‘Apple’, ‘Banana’, ‘Cherry’];

const listItems = fruits.map((fruit, index) => (


<li key={index}>{fruit}</li>
));

return <ul>{listItems}</ul>;

JSX vs HTML – Key Differences:

Best Practices with JSX:


• Keep JSX code clean and readable.
• Break down complex UI into components.
• Use meaningful keys in lists (key={index} is acceptable but not ideal).
• Wrap multi-line JSX in () for clarity.

Summary:
• JSX allows writing HTML-like syntax in React components.
• It is transpiled to JavaScript using React.createElement.
• JSX improves readability, maintainability, and dynamic rendering.
• You can embed expressions, conditionals, and loops inside JSX.

10. React Element as JSX:


What is a React Element?
A React Element is a plain JavaScript object that represents a DOM node or
a component. It is the building block of React applications.
• JSX is just syntactic sugar for creating these elements.
• React Elements are immutable, meaning once created, they can’t be
changed.

JSX Creates React Elements:


When you write JSX like:
const element = <h1>Hello, React!</h1>;
It gets compiled (transpiled) into:
const element = React.createElement(‘h1’, null, ‘Hello, React!’);
And that returns a React Element:
{
type: ‘h1’,
props: {
children: ‘Hello, React!’
}
}
JSX is Just a Shortcut for React.createElement():
Example 1 – JSX:
const greeting = <h1>Hello, Aditya!</h1>;
Equivalent Without JSX:
const greeting = React.createElement('h1', null, 'Hello, Aditya!');

Why Use JSX for Creating React Elements?

JSX React Element with Props and Nesting


JSX:
const element = <h1 className="title">Welcome</h1>;
Equivalent:
const element = React.createElement('h1', { className: 'title' }, 'Welcome');
JSX with Nesting:
const element = (
<div>
<h1>Hello</h1>
<p>This is a paragraph.</p>
</div>
);
Equivalent:
const element = React.createElement(
'div',
null,
React.createElement('h1', null, 'Hello'),
React.createElement('p', null, 'This is a paragraph.')
);

React Element vs JSX vs Component:

When JSX is Evaluated:


• At compile time, Babel converts JSX into React.createElement() calls.
• At runtime, React compares the new elements with the previous ones
using Virtual DOM and updates the real DOM.

Summary:
• JSX is a declarative way to define React Elements.
• JSX code is compiled to React.createElement() calls.
• The output of JSX is always a React Element – an object describing
what React should render.
• JSX improves developer experience, while React Elements power
React’s rendering engine.

You might also like