Horje
How React Works?

React is a tool made by Facebook to help create user interfaces, especially for single-page applications where the interface changes often and data updates a lot. It lets developers build reusable pieces of the interface, each managing its own state, which makes apps more efficient and simpler to maintain.

These are the following topics that we are going to discuss:

What is React often compared with?

React is often compared to other tools like Angular and Vue.js. Angular is a complete framework with specific rules on how to build applications. React, however, is more focused just on the user interface and gives you more freedom to mix it with other tools. Vue.js is known for being easy to learn and simple to use, making it a good option if you want something straightforward.

How does React work?

React uses a component-based architecture. Components are self-contained units of UI, each responsible for rendering a small, reusable piece of the user interface. These components can be composed together to build complex UIs.

Why Use React?

  • Component Reusability: Components are independent and reusable, enhancing code maintainability.
  • Virtual DOM: React uses a virtual DOM to optimize rendering, improving performance by updating only the necessary parts of the UI.
  • JSX: It allows you to write HTML-like syntax within JavaScript, making it easier to visualize and integrate UI components.
  • Ecosystem: React has a vast ecosystem with tools and libraries that extend its capabilities, such as Redux for state management and React Router for routing.

What Can You Build with React?

  • Single-Page Applications (SPAs): React is ideal for SPAs where content is dynamically updated without reloading the entire page.
  • Progressive Web Apps (PWAs): React can be used to build PWAs that offer native-like experiences on the web.
  • Mobile Apps: React Native extends React to build mobile applications for iOS and Android platforms using JavaScript and React principles.

How to Make React Work?

To start using React, you typically set up a development environment using tools like create-react-app

Step 1: Install Node.js

Ensure Node.js is installed on your system.

Step 2: Create a New React Application

Use npx create-react-app my-app to set up a new React project.

Step 3: Develop Components

Create and organize your UI into components, which can be either class components or functional components with hooks.

Step 4: Render Components

Use ReactDOM to render these components into the HTML page.

What are Class Components?

Class components are traditional React components that extend from React.Component and must contain a render method. They can manage their own state and lifecycle methods.

Example: In this example, we define a class component MyComponent that renders a simple “Geeks For Geeks” message.

import React, { Component } from 'react';

class MyComponent extends Component {
render() {
return <div>Geeks For Geeks</div>;
}
}

export default MyComponent;

Output:

Screenshot-2024-07-15-072119

What are Functional Components in Hooks?

Functional components are simple JavaScript functions that return JSX. With the introduction of Hooks in React 16.8, functional components can manage state and side effects.

Example: In this example, we define a functional component MyComponent that uses the useState hook to manage a count state. The component renders a button that, when clicked, increments the count.

import React, { useState } from 'react';

const MyComponent = () => {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};

export default MyComponent;

Output:

Screenshot-2024-07-15-072333

What is JSX?

JSX is a syntax extension for JavaScript that looks similar to XML. It allows you to write HTML-like code within JavaScript, which React then transforms into React.createElement calls.

Example: In this example, we use JSX to create an h1 element with the text “Hello, GFG”. React converts this JSX into a React.createElement call.

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

Output:

Screenshot-2024-07-15-072820

What is React.createElement?

React.createElement is a way to create React elements without JSX. It’s useful for more dynamic use cases.

Example: In this example, we use React.createElement to create an h1 element with the text “GFG”. This approach does not use JSX.

const element = React.createElement('h1', null, 'GFG');

Output:

Screenshot-2024-07-15-073009

What is Virtual DOM?

The Virtual DOM (VDOM) is an in-memory representation of the real DOM. React uses it to optimize the process of updating the user interface by minimizing direct manipulations of the actual DOM.

How It Works?

Step 1: Render Phase: When a React component renders, it creates a Virtual DOM representation of the UI.

Step 2: Diffing Algorithm: React compares the current Virtual DOM with a previous version to determine what has changed.

Step 3: Reconciliation: React applies only the necessary changes to the real DOM, improving performance and minimizing reflows and repaints.

import React, { useState } from 'react';

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

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};

export default App;

What is Component Lifecycle?

React components go through several lifecycle phases, which are hooks or methods that allow you to run code at specific points during a component’s existence.

Lifecycle Phases

Step 1: Mounting

  • When a component is being created and inserted into the DOM.
  • componentDidMount (Class Component)
  • useEffect with an empty dependency array (Functional Component)

Step 2: Updating

  • When a component is being re-rendered due to changes in props or state.
  • componentDidUpdate (Class Component)
  • useEffect with specific dependencies (Functional Component)

Step 3: Unmounting

  • When a component is being removed from the DOM.
  • componentWillUnmount (Class Component)
  • Cleanup function inside useEffect (Functional Component)
import React, { useEffect, useState } from 'react';

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

useEffect(() => {
console.log('Component mounted or updated');
return () => console.log('Component will unmount');
}, [count]);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};

export default App;

What is One-Way Data Binding?

One-way data binding means that data flows in a single direction—from parent components to child components. The child components receive data through props and can only communicate changes back to the parent using callback functions.

  • Props: Data is passed from a parent component to a child component via props.
  • State: State changes within a component are managed internally and can trigger re-renders.
import React, { useState } from 'react';

const ChildComponent = ({ count, onIncrement }) => {
return (
<div>
<p>Count: {count}</p>
<button onClick={onIncrement}>Increment</button>
</div>
);
};

const ParentComponent = () => {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);

return <ChildComponent count={count} onIncrement={increment} />;
};

export default ParentComponent;

What is Reconciliation?

Reconciliation is the process React uses to update the UI efficiently. It involves comparing the Virtual DOM with the previous version to determine the minimum number of changes required.

  • Diffing: React compares the current Virtual DOM tree with the previous one.
  • Update Calculation: React calculates the optimal way to update the real DOM.
  • Patch Application: React applies the calculated updates to the real DOM.
import React, { useState } from 'react';

const App = () => {
const [items, setItems] = useState(['Item 1', 'Item 2']);

const addItem = () => {
setItems([...items, `Item ${items.length + 1}`]);
};

return (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={addItem}>Add Item</button>
</div>
);
};

export default App;

What is Component-Based Architecture?

Component-based architecture is a design pattern where the UI is divided into independent, reusable components. Each component encapsulates its own structure, style, and behavior.

Benefits:

  • Reusability: Components can be reused across different parts of the application.
  • Encapsulation: Components manage their own state and logic.
  • Maintainability: Smaller, modular components are easier to manage and debug.
import React from 'react';

const Header = () => <header>Header</header>;
const MainContent = () => <main>Main Content</main>;
const Footer = () => <footer>Footer</footer>;

const App = () => (
<div>
<Header />
<MainContent />
<Footer />
</div>
);

export default App;

What is Fibre Architecture?

Fibre is a complete rewrite of React’s reconciliation algorithm introduced in React 16. It improves React’s ability to handle complex updates and interruptions efficiently.

  • Incremental Rendering: Allows React to pause and resume rendering work, improving performance for complex updates.
  • Priority Levels: Different types of updates (e.g., animations vs. data changes) can be assigned different priority levels.
  • Error Handling: Provides better mechanisms for catching and recovering from errors during rendering.

Hooks

Hooks are functions that let you use state and other React features without writing a class. They were introduced in React 16.8 to simplify component logic and reuse stateful logic.

  • useState: Manages state in functional components.
  • useEffect: Performs side effects like data fetching or subscriptions.
  • useContext: Accesses context values.
import React, { useState, useEffect } from 'react';

const ExampleComponent = () => {
const [count, setCount] = useState(0);

useEffect(() => {
console.log('Component mounted or updated');
return () => console.log('Component will unmount');
}, [count]);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

export default ExampleComponent;

Context API

The Context API is a feature in React that allows you to share data across the entire component tree without having to pass props down manually at every level. It is useful for managing global state, such as user authentication, themes, or settings.

Step 1. Create Context: First, create a new context

import React, { createContext, useState } from 'react';

const MyContext = createContext();

const MyProvider = ({ children }) => {
const [value, setValue] = useState('Hello, World!');

return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};

export { MyContext, MyProvider };

Step 2. Consume Context: You can consume the context in a component using useContext.

import React, { useContext } from 'react';
import { MyContext } from './MyProvider';

const MyComponent = () => {
const { value, setValue } = useContext(MyContext);

return (
<div>
<p>{value}</p>
<button onClick={() => setValue('New Value')}>Change Value</button>
</div>
);
};

export default MyComponent;

Step 3: App Component

import React from 'react';
import { MyProvider } from './MyProvider';
import MyComponent from './MyComponent';

const App = () => {
return (
<MyProvider>
<MyComponent />
</MyProvider>
);
};

export default App;

Steps to Create Application

To create a React application, you can use the create-react-app CLI tool, which sets up everything you need.

Step 1: Install Node.js

First, ensure you have Node.js installed. You can download it from nodejs.org.

Step 2: Create a New React Application

Open your terminal and run the following command:

npx create-react-app my-app

This will create a new directory called my-app with all the necessary files and dependencies.

Step 3: Navigate to the Application Directory

cd my-app

Step 4: Start the Development Server

npm start

This will start the development server and open your new React application in the default web browser.

Build Your App Layout with React Components

Updated Dependencies:

dependencies: {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Project Structure:

Screenshot-2024-07-19-162212

Example: This example shows the implementation of the above explained steps.

JavaScript
// MainSection.js
import React from 'react';

const MainSection = () => {
    return (
        <section className="main-section">
            <h2>Welcome to GFG</h2>
            <p>This is the main content section of the application.</p>
        </section>
    );
};

export default MainSection;
JavaScript
// Header.js
import React from 'react';

const Header = () => {
    return (
        <header className="header">
            <h1>Geeks For Geeks</h1>
            <nav>
                <ul>
                    <li><a href="/">Home</a></li>
                    <li><a href="/about">About</a></li>
                    <li><a href="/contact">Contact</a></li>
                </ul>
            </nav>
        </header>
    );
};

export default Header;
JavaScript
// Footer.js
import React from 'react';

const Footer = () => {
    return (
        <footer className="footer">
            <p>&copy; 2024 GeeksForGeeks. All rights reserved.</p>
        </footer>
    );
};

export default Footer;
JavaScript
// App.js
import React from 'react';
import Header from './Components/Header';
import MainSection from './Components/MainSection';
import Footer from './Components/Footer';

const App = () => {
    return (
        <div className="app">
            <Header />
            <MainSection />
            <Footer />
        </div>
    );
};

export default App;

Output:

Screenshot-2024-07-17-195847



Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Explain The Benefits And Challenges Of Caching And Offline Support in Redux Explain The Benefits And Challenges Of Caching And Offline Support in Redux
Benefits of Using ReactJS For Custom Web Development Benefits of Using ReactJS For Custom Web Development
Understanding Unique Keys For Array Children in ReactJS Understanding Unique Keys For Array Children in ReactJS
Difference between NavLink and Link tag in React Router Difference between NavLink and Link tag in React Router
Next.js Playwright Testing Next.js Playwright Testing

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18