Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

React.js_ Introduction and How It Works

React.js, developed by Facebook, addresses issues in traditional web development such as complex DOM manipulation, performance bottlenecks, and poor code organization by utilizing a component-based architecture and a virtual DOM. It allows for efficient updates and reusability of components, making it easier to manage state and build user interfaces. Key features include JSX syntax, a large ecosystem, and a clear one-way data flow.

Uploaded by

sathvikareddynew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

React.js_ Introduction and How It Works

React.js, developed by Facebook, addresses issues in traditional web development such as complex DOM manipulation, performance bottlenecks, and poor code organization by utilizing a component-based architecture and a virtual DOM. It allows for efficient updates and reusability of components, making it easier to manage state and build user interfaces. Key features include JSX syntax, a large ecosystem, and a clear one-way data flow.

Uploaded by

sathvikareddynew
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

React.

js: Introduction and How It Works

Why React Was Invented


React was invented by Facebook (now Meta) in 2011 and released to the public in 2013 to
solve several problems with traditional web development:

1. DOM Manipulation Complexity


• Vanilla JavaScript required manual DOM updates using methods like
document.getElementById() and document.createElement()
• This led to complex, error-prone code that was hard to maintain
• Tracking which parts of the DOM needed updates was difficult
2. Performance Issues
• Direct DOM manipulation is slow, especially for complex UI changes
• Applications would become sluggish as they grew in complexity
• Frequent updates to the DOM caused performance bottlenecks
3. Code Organization Problems
• UI code became difficult to organize and reuse
• No standard way to create reusable UI components
• Logic and UI were often mixed together in complex ways

Challenges in Traditional Web Development

DOM Manipulation Code Organization


Complexity Problems

Inefficiencies in
Difficulty in
Manual Updates Traditional Web
Reusability
Development

Error-Prone Code Mixed Logic and UI

Sluggish Applications

Slow Direct
Manipulation

Performance Issues

Vanilla JavaScript vs React


Vanilla JavaScript Approach:

// Creating and updating UI with vanilla JavaScript


document.getElementById('app').innerHTML = '<h1>Student List</h1>';

const studentList = document.createElement('ul');


document.getElementById('app').appendChild(studentList);

// Adding a student
function addStudent(name, rollNo) {
const studentItem = document.createElement('li');
studentItem.textContent = `${name} (${rollNo})`;

// Add delete button


const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.onclick = function() {
studentItem.remove();
};

studentItem.appendChild(deleteBtn);
studentList.appendChild(studentItem);
}

// Event listener for form


document.getElementById('student-form').addEventListener('submit', function(e) {
e.preventDefault();
const name = document.getElementById('name').value;
const rollNo = document.getElementById('roll-no').value;
addStudent(name, rollNo);
document.getElementById('name').value = '';
document.getElementById('roll-no').value = '';
});

React Approach:

// The same functionality with React


function StudentApp() {
const [students, setStudents] = useState([]);
const [name, setName] = useState('');
const [rollNo, setRollNo] = useState('');

const addStudent = (e) => {


e.preventDefault();
setStudents([...students, { name, rollNo }]);
setName('');
setRollNo('');
};

const deleteStudent = (index) => {


const newStudents = [...students];
newStudents.splice(index, 1);
setStudents(newStudents);
};

return (
<div>
<h1>Student List</h1>

<form onSubmit={addStudent}>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
/>
<input
value={rollNo}
onChange={(e) => setRollNo(e.target.value)}
placeholder="Roll No"
/>
<button type="submit">Add Student</button>
</form>

<ul>
{students.map((student, index) => (
<li key={index}>
{student.name} ({student.rollNo})
<button onClick={() => deleteStudent(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

How React Works Behind the Scenes


1. The Virtual DOM
• React creates a lightweight copy of the actual DOM in memory
• When state changes, React:
• Creates a new Virtual DOM tree
• Compares it with the previous one (diffing)
• Calculates the minimum number of changes needed
• Updates only those specific parts of the real DOM

React Virtual DOM Update Process

Create Virtual New Virtual Calculate


DOM DOM Tree Changes

State Change Diffing Update Real


Process DOM

2. Component-Based Architecture
• Everything in React is a component
• Components can be:
• Function components (modern approach)
• Class components (older approach)
• Components can be nested and reused
• Each component manages its own state and props

Mastering React Components

State and
Props Function
Management Components
Highlights the Represent the
component's modern approach
control over its to building
own data and components in
configuration. React.

React
Components
Class
Reusability
Components
Emphasizes the
efficiency of using Reflect the older,
components traditional method
multiple times. of creating
components.

Nesting
Illustrates the
ability to embed
components within
one another.

3. React's Rendering Flow

Initial Render:
JSX → React.createElement() → Virtual DOM → Real DOM

Updates:
State Change → Re-render Component → New Virtual DOM →
Diffing with Previous Virtual DOM → Minimal Real DOM Updates

React Rendering and Update Process

The process begins with


Initial Render rendering the component for
the first time.

JSX is transformed into a React


element. JSX to React.createElement()

A virtual representation of the


Virtual DOM Creation DOM is created.

The real DOM is updated to


reflect the virtual DOM. Real DOM Update

A change in state triggers the


State Change update process.

The component is re-rendered


to reflect state changes. Re-render Component

A new virtual DOM is created


New Virtual DOM for the updated component.

The new virtual DOM is


compared with the previous Diffing Process
one.

Only necessary updates are


Minimal Real DOM Updates made to the real DOM.

4. JSX
• JSX is a syntax extension that looks like HTML but is actually JavaScript
• Gets transformed into React.createElement() calls during build
• Allows you to write UI components in a familiar HTML-like syntax
• Example: <div className="container">Hello {name}!</div>

Starting Point and Setup Flow


1. Project Setup

# Create a new React app


npx create-react-app my-first-app

# Navigate to project folder


cd my-first-app

# Start development server


npm start

2. Key Files in a React Project


• index.js: The entry point of a React application
• App.js: The root component that contains other components
• package.json: Lists dependencies and scripts
• public/index.html: The HTML template
3. Component Lifecycle Flow
Modern React uses Hooks to manage lifecycle:
• useState: Manages component state
• useEffect: Handles side effects (like data fetching, DOM manipulation)
• useContext: Accesses context API for sharing data
• useRef: References DOM elements or persists values without re-render
4. State Management Process
1. Initialize state with useState
2. Update state with state setter function
3. Component re-renders automatically
4. React updates the DOM efficiently

Why React Is Better Than Vanilla JS


1. Declarative UI: You describe what the UI should look like at any given state, not how
to change it
2. Component Reusability: Build encapsulated components that manage their own state
3. Efficient Updates: Virtual DOM ensures minimal DOM operations
4. One-Way Data Flow: Makes code more predictable and easier to debug
5. Large Ecosystem: Huge community, libraries, and tools

Common React Terms


• Props: Data passed from parent to child components
• State: Component's internal data that can change over time
• Hooks: Functions that let you use React features in function components
• JSX: JavaScript XML syntax used to write React components
• Rendering: The process of converting React elements to DOM nodes
• Components: Reusable, self-contained pieces of UI

You might also like