> For the complete documentation index, see [llms.txt](https://www.ankitavirani.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.ankitavirani.com/experience/frontend/react.md).

# React

## 📚 Introduction to React JS

React JS is a powerful JavaScript library for building user interfaces, particularly single-page applications. It's known for its efficiency, flexibility, and component-based architecture. This document will explore advanced React concepts, architectural patterns, and real-world applications.

#### Why React?

* **Component-Based Architecture:** Encourages code reusability and maintainability.
* **Virtual DOM:** Improves performance by minimizing DOM manipulations.
* **Declarative Style:** Focuses on describing the desired UI state rather than imperative updates.
* **Large and Active Community:** Extensive support, libraries, and tools available.
* **JSX:** Makes code more readable and intuitive.

#### Important Features

* **React Hooks:** Allow you to use state and other React features without writing classes.
* **Context API:** Provides a way to share data across components without prop drilling.
* **React Router:** For handling navigation in single-page applications.
* **Redux:** Popular state management library for complex applications.
* **Server-Side Rendering (SSR):** Improves SEO and initial page load performance.

#### Creating a React Page

Bash

```
npx create-react-app my-app
cd my-app
npm start
```

This will create a new React project, install dependencies, and start a development server.

**Note:** This is a basic overview. React offers many more features and concepts.

**Would you like to delve deeper into a specific area of React, such as React Hooks, Redux, or building a particular type of application?**

### 🏗️ React Architecture

React follows a component-based architecture, which allows for reusable UI elements. Let's visualize this with a diagram:

<figure><img src="/files/O810aq4FUukgMmRPNbIC" alt=""><figcaption></figcaption></figure>

This diagram represents a typical e-commerce application structure in React. Each box represents a component, and the arrows show the hierarchy and relationships between components.

### 🔧 Core React Concepts

#### 1. JSX (JavaScript XML)

JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. Here's an example:

```jsx
const element = <h1>Hello, {name}</h1>;


import React from 'react';

function Welcome() {
    return <h1>Welcome to React!</h1>;
}

export default Welcome;
```

#### 2. Components and Props

**Functional Components**

Functional components are simpler and easier to understand. They are defined as JavaScript functions and receive props as arguments.

```javascript
// FunctionalComponent.js
import React from 'react';

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

export default FunctionalComponent;
```

**Class Components**

Class components offer more features and are used for components that require state or lifecycle methods. They are defined using ES6 classes.

```javascript
// ClassComponent.js
import React, { Component } from 'react';

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

export default ClassComponent;
```

Components are the building blocks of React applications. They can be functional or class-based. Props are used to pass data between components.

```jsx
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
```

#### 3. State and Lifecycle

State is used to store component-specific data that can change over time. The lifecycle methods allow you to run code at specific points in a component's life.

```jsx
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
```

#### 4. Hooks

Hooks allow functional components to use state and other React features. The most common hooks are useState and useEffect.

```jsx
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

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

### 🔄 React Component Lifecycle

Understanding the React component lifecycle is crucial for optimizing performance and managing side effects. Here's a diagram illustrating the lifecycle of a class component:

<figure><img src="/files/YdMdBgStOIiIdzyo7J0D" alt=""><figcaption></figcaption></figure>

For functional components, we use hooks to manage lifecycle-like behavior. The most common hooks are useState, useEffect, and useContext.

### 📊 Detailed Component Lifecycle

#### 1. Mounting Phase

The mounting phase occurs when a component is being added to the DOM. It involves the following methods:

* **constructor(props)**: Initializes state and binds methods.
* **render()**: Returns JSX to be rendered.
* **componentDidMount()**: Runs after the component is mounted to the DOM.

```jsx
class MountingComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: null };
  }

  componentDidMount() {
    fetchData().then(data => this.setState({ data }));
  }

  render() {
    return <div>{this.state.data ? 'Data loaded' : 'Loading...'}</div>;
  }
}
```

#### 2. Updating Phase

The updating phase occurs when a component's state or props change. It involves these methods:

* **shouldComponentUpdate(nextProps, nextState)**: Decides if the component should re-render.
* **render()**: Re-renders the component with updated data.
* **componentDidUpdate(prevProps, prevState)**: Runs after the component updates.

```jsx
class UpdatingComponent extends React.Component {
  shouldComponentUpdate(nextProps) {
    return this.props.value !== nextProps.value;
  }

  componentDidUpdate(prevProps) {
    if (this.props.value !== prevProps.value) {
      console.log('Value changed');
    }
  }

  render() {
    return <div>{this.props.value}</div>;
  }
}
```

#### 3. Unmounting Phase

The unmounting phase occurs when a component is being removed from the DOM. It involves one method:

* **componentWillUnmount()**: Runs just before the component is unmounted and destroyed.

```jsx
class UnmountingComponent extends React.Component {
  componentWillUnmount() {
    console.log('Component is about to be unmounted');
    // Clean up any subscriptions or timers here
  }

  render() {
    return <div>I'm still here!</div>;
  }
}
```

#### 4. Error Handling Phase

This phase is invoked when there's an error during rendering, in a lifecycle method, or in the constructor of any child component.

* **static getDerivedStateFromError(error)**: Used to render a fallback UI after an error has been thrown.
* **componentDidCatch(error, info)**: Used to log error information.

```jsx
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
```

### 📊 Lifecycle Diagram

Here's an architecture diagram with a landscape view representing the React component lifecycle:

<figure><img src="/files/rONTfwkpppWkD5Afm07k" alt=""><figcaption></figcaption></figure>

This architecture diagram presents a landscape view of the React component lifecycle, showcasing the relationships between different layers:

* User Interface Layer: Where user interactions originate
* React Component Layer: Contains the component instance and its props and state
* Lifecycle Methods Layer: Includes mounting, updating, and unmounting methods
* Rendering Layer: Shows the process from Virtual DOM to Actual DOM

The diagram illustrates how user interactions trigger changes in the React component, which then flow through the lifecycle methods and rendering process, ultimately updating the user interface.

### 🔀 State Management

For complex applications, state management becomes crucial. While React's built-in state management is sufficient for many cases, larger applications often benefit from additional libraries like Redux or MobX.

#### Redux Architecture

<figure><img src="/files/xXIPPOWff4MOnz1kS2vw" alt=""><figcaption></figcaption></figure>

This diagram illustrates the unidirectional data flow in Redux, a popular state management library for React applications.

### 🌐 React Router for Navigation

React Router is the standard routing library for React. It keeps your UI in sync with the URL, allowing you to create a single-page application with navigation without the page refreshing.

```jsx
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/users">Users</Link></li>
          </ul>
        </nav>

        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/users" component={Users} />
      </div>
    </Router>
  );
}
```

### 🔍 Advanced React Patterns

#### 1. Render Props

The render prop pattern allows you to share code between components using a prop whose value is a function.

```jsx
class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

// Usage
<Mouse render={({ x, y }) => (
  <h1>The mouse position is ({x}, {y})</h1>
)}/>
```

#### 2. Higher-Order Components (HOCs)

HOCs are functions that take a component and return a new component with additional props or behavior.

```jsx
function withLogger(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component is mounted');
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

// Usage
const EnhancedComponent = withLogger(MyComponent);
```

### 🚀 Performance Optimization

React provides several ways to optimize the performance of your applications:

#### 1. React.memo

React.memo is a higher-order component that can be used to wrap functional components to prevent unnecessary re-renders.

```jsx
const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});
```

#### 2. useMemo and useCallback

These hooks are used to memoize values and functions respectively, preventing unnecessary recalculations or re-creations.

```jsx
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
```

### 🌟 Real-World Example: Building a Todo App

Let's create a simple todo app to demonstrate these concepts in action.

```jsx
import React, { useState, useCallback, useMemo } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = useCallback(() => {
    if (input) {
      setTodos(prevTodos => [...prevTodos, { id: Date.now(), text: input, completed: false }]);
      setInput('');
    }
  }, [input]);

  const toggleTodo = useCallback((id) => {
    setTodos(prevTodos =>
      prevTodos.map(todo =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  }, []);

  const completedCount = useMemo(() => {
    return todos.filter(todo => todo.completed).length;
  }, [todos]);

  return (
    <div>
      <h1>Todo App</h1>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Add a todo"
      />
      <button onClick={addTodo}>Add</button>
      <ul>
        {todos.map(todo => (
          <li
            key={todo.id}
            onClick={() => toggleTodo(todo.id)}
            style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
          >
            {todo.text}
          </li>
        ))}
      </ul>
      <p>Completed todos: {completedCount}</p>
    </div>
  );
}

export default TodoApp;
```

This example demonstrates the use of various React hooks (useState, useCallback, useMemo) and showcases how to manage state, handle user input, and optimize performance in a real-world scenario.

### 🚀 Why React Was Introduced

React was introduced by Facebook in 2013 to address several challenges in building large-scale web applications:

* **Efficient DOM manipulation:** React's virtual DOM optimizes updates, reducing expensive direct DOM manipulations.
* **Component-based architecture:** React promotes reusable, modular code through its component system.
* **Unidirectional data flow:** React's one-way data binding simplifies debugging and improves application predictability.
* **Performance:** React's efficient update mechanism allows for building high-performance user interfaces.
* **Developer experience:** React's declarative syntax and powerful ecosystem enhance developer productivity.

These features have made React a popular choice for building modern web applications, addressing pain points in traditional web development approaches.

###

***

Feel free to adjust this content based on your specific experience and projects with React.js!


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ankitavirani.com/experience/frontend/react.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
