{"id":49477174,"url":"https://github.com/sidneyshafer/complete-react-guide","last_synced_at":"2026-04-30T20:35:16.415Z","repository":{"id":176661575,"uuid":"655705832","full_name":"sidneyshafer/complete-react-guide","owner":"sidneyshafer","description":"Complete guide to building React applications","archived":false,"fork":false,"pushed_at":"2026-02-15T22:07:57.000Z","size":5144,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-04-30T20:35:11.422Z","etag":null,"topics":["react-hooks","react-router","reactjs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sidneyshafer.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-06-19T12:36:56.000Z","updated_at":"2026-02-15T22:08:03.000Z","dependencies_parsed_at":"2025-01-25T23:27:25.331Z","dependency_job_id":"0a7db54d-13ab-44bf-836e-8627b7642910","html_url":"https://github.com/sidneyshafer/complete-react-guide","commit_stats":null,"previous_names":["sidneyshafer/complete-react-guide"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sidneyshafer/complete-react-guide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sidneyshafer%2Fcomplete-react-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sidneyshafer%2Fcomplete-react-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sidneyshafer%2Fcomplete-react-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sidneyshafer%2Fcomplete-react-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sidneyshafer","download_url":"https://codeload.github.com/sidneyshafer/complete-react-guide/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sidneyshafer%2Fcomplete-react-guide/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32476682,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"ssl_error","status_checked_at":"2026-04-30T13:12:06.837Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react-hooks","react-router","reactjs"],"created_at":"2026-04-30T20:35:15.592Z","updated_at":"2026-04-30T20:35:16.406Z","avatar_url":"https://github.com/sidneyshafer.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003eComplete guide to building applications in React.\n\n# Table of Contents\n* **[Introduction to React](#introduction-to-react)**\n* **[Tech Stack \u0026 Prerequisites](#tech-stack--prerequisites)**\n* **[Quick Start](#quick-start)**\n* **[Creating a New React App](#creating-a-new-react-app)**\n* **[React App Usage](#react-app-usage)**\n* **[Base React App](#base-react-app)**\n* **[React Component Types](#react-component-types)**\n* **[Introduction Project](#introduction-project)**\n* **[CSS Modules for Styling](#css-modules-for-styling)**\n* **[React Fragments](#react-fragments)**\n* **[Overview of React Hooks](#overview-of-react-hooks)**\n* **[State Management](#state-management)**\n* **[React Side Effects](#react-side-effects)**\n* **[Performance Optimization](#performance-optimization)**\n* **[Sending HTTP Requests](#sending-http-requests)**\n* **[All React Demo Projects](#all-react-demo-projects)**\n\n---\n\n## Introduction to React\n\n**[React](https://react.dev/)** is a JavaScript library for building user interfaces. It is developed and maintained by **[Meta (Facebook)](https://github.com/facebook)** and is widely used for creating fast, scalable, and interactive web applications.\n\n**Key Features of React**\n\n:white_check_mark: **Component-Based Architecture** – Improve maintainability with reusable components.\n\n:white_check_mark: **Declarative UI** – Describe how the UI should look, and React updates it efficiently.\n\n:white_check_mark: **Virtual DOM** – Optimizes performance by updating only necessary parts of the UI, which allows for fast rendering.\n\n:white_check_mark: **Unidirectional Data Flow** – Data flows from parent to child components, ensuring predictable state management.\n\n:white_check_mark: **Hooks \u0026 Functional Components** – Simplifies state and side-effects management without needing class components.\n\n:white_check_mark: **Strong Ecosystem** – Works well with libraries like **React Router**, **Redux**, and more, with **[strong community support](https://github.com/reactjs)** and widespread adoption.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Tech Stack \u0026 Prerequisites\n\n### Core Technologies\n| Technology | Version | Description |\n|------------|---------|-------------|\n| React | 19.x | UI library for building component-based interfaces |\n| React DOM | 19.x | React rendering for web browsers |\n| React Scripts | 5.0.1 | Create React App build tooling |\n| React Router DOM | 7.x | Client-side routing for React applications |\n| Redux Toolkit | 2.x | State management with modern Redux patterns |\n| Next.js | 16.x | React framework for server-side rendering |\n\n### Prerequisites\n- **Node.js** (v18 or higher recommended)\n- **npm** (v9 or higher) or **yarn**\n- Basic knowledge of JavaScript (ES6+)\n- Familiarity with HTML and CSS\n\n### Development Tools\n- Code editor (VS Code recommended)\n- Browser with React DevTools extension\n- Git for version control\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Quick Start\n\nClone the repository and navigate to any project folder:\n\n```bash\ngit clone https://github.com/your-username/complete-react-guide.git\ncd complete-react-guide/base-react-app\n```\n\nInstall dependencies and start the development server:\n\n```bash\nnpm install\nnpm start\n```\n\nThe app will open at `http://localhost:3000`.\n\n\u003e [!TIP]\n\u003e Each project folder contains its own `readme.md` with specific instructions and documentation.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Creating a New React App\n\u003eInstructions for creating a new React app using **[Node Package Manager (`npm`)](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager)**.\n\n* [Overview of Node Package Manager](#creating-new-project-npm-overview)\n* [Environment Setup](#creating-new-project-setup)\n* [Project Structure](#creating-new-project-structure)\n* [File Overview](#creating-new-project-file-overview)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [new-react-app](/new-react-app)\n\n### \u003ca name=\"creating-new-project-npm-overview\"\u003eOverview of Node Package Manager\u003c/a\u003e\n\nNode Package Manager (`npm`) is a package manager for JavaScript that helps developers install, manage, and share dependencies. \n\nIt is the default package manager for **[Node.js](https://nodejs.org/en)** and is widely used in web development.\n\nThis includes React applications which rely on various dependencies (`react` and `react-dom`) and other libraries for state management, routing, UI components, and more. `npm` helps in managing these dependencies efficiently.\n\nIn a React environment managed by `npm`, the `node_modules` directory contains all installed `npm` packages used by the app.\n\n### \u003ca name=\"creating-new-project-setup\"\u003eEnvironment Setup\u003c/a\u003e\n\nThe `npm` command for creating a new React app is:\n```\nnpx create-react-app my-new-app\n```\n**`npx`**\n* Package runner that comes with npm 5.2+ and higher.\n* Runs the `create-react-app` package without installing it globally.\n\n**`create-react-app`**\n* Tool provided by the React team to quickly scaffold a React project with a pre-configured setup.\n\n**`my-new-app`**\n* Name of the new project folder. Replace `my-new-app` with desired project name.\n\n### \u003ca name=\"creating-new-project-structure\"\u003eProject Structure\u003c/a\u003e\n```\nmy-new-app/\n├── public/\n│   ├── favicon.ico\n│   ├── index.html\n│   ├── logo192.png\n│   ├── logo512.png\n│   ├── manifest.json\n│   └── robots.txt\n├── src/\n│   ├── App.css\n│   ├── App.js\n│   ├── App.test.js\n│   ├── index.css\n│   ├── index.js\n│   ├── logo.svg\n│   ├── reportWebVitals.js\n│   └── setupTests.js\n├── .gitignore\n├── package.json\n└── README.md\n```\n\n### \u003ca name=\"creating-new-project-file-overview\"\u003eFile Overview\u003c/a\u003e\n**`public`/**\n\n* Contains static assets and the root HTML file for the app.\n    * **`index.html`**\n        * Main HTML file where the React app is mounted.\n        * The `\u003cdiv id=\"root\"\u003e\u003c/div\u003e` element acts as the entry point for React to inject the app.\n        * You can add meta tags, external scripts, or other HTML configurations here.\n    * **`logo192.png`** *and* **`logo512.png`**\n        * Logos displaying the specific React symbol (these are usually discarded).\n    * **`favicon.ico`** *and* **`manifest.json`**\n        * Used to provide metadata for the app.\n        * The `favicon` is used as the small icon displayed in a browser tab.\n    * **`robots.txt`**\n        * Tells search engine crawlers which URLs the crawler can access on your site.\n\u003e [!TIP]\n\u003e :pushpin: Check out the project [documentation](/robots.txt.md) for information on the use of `robots.txt`.\n\n**`src`/**\n\n* Contains all the main application logic and components.\n    * **`index.js`**\n        * Entry point of the React app.\n        * Renders the `\u003cApp /\u003e` component into the DOM root element.\n    * **`index.css`**\n        * Global CSS styles applied across the app.\n        * Imported into the `index.js` file: `import './index.css';`.\n    * **`App.js`**\n        * The root React component.\n        * Defines the main structure of the app by combining child components.\n    * **`App.css`**\n        * Styles specific to the `App.js` component.\n        * Used in `App.js` component with the `import` statement: `import './App.css';`.\n    * **`App.test.js`**\n        * Contains test cases for the App component using tools like Jest or React Testing Library.\n    * **`reportWebVitals.js`**\n        * Used to measure performance metrics of the app.\n    * **`setupTests.js`**\n        * Allows configuration of testing environment before any tests are run.\n        * Commonly used with testing libraries like Jest and React Testing Library.\n\n**`package.json`**\n\n* Contains metadata about the app and its dependencies.\n\n**`.gitignore`**\n\n* Configuration file that specifies which files and directories Git should ignore in version control. \n* These often include `node_modules`, `.DS_Store`, production files, etc.\n\n**`README.md`**\n\n* A markdown document that provides essential information about the project. \n* Typically the first thing users or collaborators see when they visit the repository on platforms like GitHub.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## :pushpin: React App Usage\n\nUsage for setting up, installing, and managing the React app environment and dependencies is outlined in the React application usage [documentation](/react.usage.md). \n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Base React App\n\u003eReact application used as the base structure for all projects in this guide.\n\n* [File Structure](#base-app-file-structure)\n* [Code Breakdown](#base-app-code-breakdown)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [base-react-app](/base-react-app)\n\n### \u003ca name=\"base-app-file-structure\"\u003eFile Structure\u003c/a\u003e\n```\nbase-react-app/\n├── public/\n    ├── index.html\n    ├── favicon.ico\n    ├── manifest.json\n    └── robots.txt\n├── src/\n    ├── assets/\n    |   ├── images/\n    |   |   ├── basic.jpg\n    ├── components/\n    |   ├── UI/\n    |   |   ├── Card.css\n    |   |   ├── Card.js\n    |   ├── Footer.css\n    |   ├── Footer.js\n    |   ├── Header.css\n    |   ├── Header.js\n    ├── App.js\n    ├── index.css\n    ├── index.js\n├── .gitignore\n├── package.json\n├── readme.md\n```\n\n### \u003ca name=\"base-app-code-breakdown\"\u003eCode Breakdown\u003c/a\u003e\n\n**The `index.js` file:**\n```js\n// import React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nimport './index.css';\nimport App from './App';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\u003cApp /\u003e);\n```\n`// import React from 'react';`\n* Imports the core React library, which is needed to use JSX (JavaScript XML) and create React components.\n* Starting from **release 17**, however, \u003cins\u003eyou no longer need this statement\u003c/ins\u003e.\n\n`import ReactDOM from 'react-dom/client';`\n* `ReactDOM` is a library that interacts with the DOM to render React components.\n* `react-dom/client` is a new way (**starting from React 18**) to manage rendering in React apps, replacing `ReactDOM.render`.\n\n`import './index.css';`\n* Imports the global CSS file for the app.\n\n`import App from './App';`\n* Imports the `App` component from `App.js`, which serves as the root component of the application. \n* The `App` component is typically where the main structure and logic of the app reside.\n\n`const root = ReactDOM.createRoot(document.getElementById('root'));`\n* This selects the root DOM element with the `id=\"root\"` (defined in `public/index.html`) and creates a React root using `ReactDOM.createRoot`.\n* The `root` serves as the entry point for the React application, allowing React to manage the DOM within this element.\n* In the `index.html` file, this is the target DOM element where the entire React app will be mounted:\n    ```html\n    \u003cdiv id=\"root\"\u003e\u003c/div\u003e\n    ```\n\n`root.render(\u003cApp /\u003e);`\n* Renders the `App` component inside the `root` element in the DOM.\n* The `\u003cApp /\u003e` syntax is JSX, representing a React component.\n\nThe summary, the `index.js` component:\n1. Sets up the environment.\n2. Renders the top-level `App` component into the `root` DOM element.\n\n---\n**The `App.js` file:**\n```js\nfunction App() {\n  return (\n    \u003cdiv\u003e\n      \u003ch2\u003eLet's get started!\u003c/h2\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n`function App()`\n* Defines a **functional component** called `App`.\n* A functional component is one of the simplest ways to define a React component. It is essentially a JavaScript function that returns JSX (HTML-like syntax).\n\n`return ( ... )`\n* The `return` statement specifies what the `App` component renders on the screen.\n* In this case, it returns a `\u003cdiv\u003e` element containing an `\u003ch2\u003e` element.\n\n`\u003cdiv\u003e` and `\u003ch2\u003e`\n* These are **JSX elements** that look similar to HTML but are actually JavaScript objects under the hood.\n* JSX allows you to write markup directly within your JavaScript code, which is then transformed into React elements during compilation.\n\n`export default App;`\n* This exports the `App` component as the default export of the file.\n* Allows other files to import `App` (in `index.js` as import `App` from `'./App';`) and use it in the application.\n* In a larger app, the `App` component would usually serve as the container for other components, managing and rendering their content.\n\nIn summary, the `App.js` component:\n1. Defines a simple functional React component.\n2. Renders an HTML structure using JSX.\n3. Is exported for use as the root component of the app.\n\n\u003e [!TIP]\n\u003e Check out the React [app usage documentation](/react.usage.md) for information on basic app usage in this project.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## React Component Types\n\n\u003eA Look at function and class component definitions.\n\n* [Function Components](#function-components)\n* [Class Components](#class-components)\n* [Comparison of Components](#comparison-of-components)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [function-class-components](/function-class-components)\n\n### Function Components\n\n**Overview:**\n\nFunction components are the most common component type used in modern React development.\n\nFunctional components are often referred to as *stateless components* because they did not have built-in state management before React Hooks were introduced.\n\nWith the introduction of React Hooks, however, functional components can now manage state.\n\nFunctional components, at their core, are JavaScript functions that accept props and return **JSX**, which is a syntax extension that allows you to write HTML-like structures within JavaScript.\n\n**Example:**\n```js\nfunction MyFunctionalComponent(props) {\n    return (\n      \u003cdiv\u003e\n        \u003ch2\u003eHello, Welcome to my Functional Component!\u003c/h2\u003e\n        \u003cp\u003e{props.text}\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n  \nexport default MyFunctionalComponent;\n```\n* Defines a functional component using the `function` keyword.\n* Accepts `props` for any data from the parent component that uses it (access `props.text` in this case).\n* The `export default` statement makes this component available for import in other files of the project.\n\n---\n### Class Components\n\n**Overview:**\n\nClass components are the \"traditional\" way of creating React components, emphasizing the used of ES6 class definitions.\n\nReact class components extend the `React.Component` class and provide methods for managing state, lifecycle events, and more.\n\nThey are becoming less common in favor of function components and hooks, but can still be useful in certain situations.\n\n**Example:**\n```js\nimport React, { Component } from 'react';\n\n// Alternatively, `extends React.Component` with only importing `React`\nclass MyClassComponent extends Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch2\u003eHello, Welcome to my Class Component!\u003c/h2\u003e\n        \u003cp\u003e{this.props.text}\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nexport default MyClassComponent;\n```\n* The component is defined as a class that extends `React.Component`.\n* `this.props` is used to access the `props` passed to the component from the `App` component.\n* The `render()` method is required in class components to return the JSX to be rendered.\n\n### Comparison of Components\n| Feature           | Class Components                       | Function Components |\n| ----------------- | -------------------------------------- | ------------------- |\n| Syntax            | ES6 classes                            | Functions           |\n| State Management  | `this.state` and `this.setState()`     | `useState` Hook     |\n| Lifecycle Methods | Separate methods (`componentDidMount`) | `useEffect` Hook    |\n| Code Complexity   | More verbose                           | Simpler and concise |\n| Performance       | Slightly heavier                       | Lightweight         |\n\n**Functional components** are the modern standard, and the preferred way for writing React components. They are lightweight, easy to understand, and powerful when combined with React Hooks.\n\n**Class components** are now less common but remain a valuable part of React's history and are still widely used in older React applications.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Introduction Project\n\u003eIntro to getting started with React apps - a simple first project.\n\n* [File Structure](#introduction-file-structure)\n* [Full Code Breakdown](#introduction-code-breakdown)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [introduction-project](/introduction-project)\n\n```\nintroduction-project/\n├── public/\n    ├── index.html\n    ├── favicon.ico\n    ├── manifest.json\n    └── robots.txt\n├── src/\n    ├── assets/\n    |   ├── images/\n    |   |   ├── ui-1.png\n    |   |   ├── ui-2.png\n    ├── components/\n    |   ├── Backdrop.js\n    |   ├── Modal.js\n    |   ├── Todo.js\n    ├── App.js\n    ├── index.css\n    ├── index.js\n├── .gitignore\n├── package.json\n├── readme.md\n```\n\n### \u003ca name=\"introduction-code-breakdown\"\u003eFull Code Breakdown\u003c/a\u003e\n\n\u003e [!NOTE]\n\u003e This section does not cover all specific code blocks in `index.js` and `App.js`. Check out the :file_folder: [base-react-app](/base-react-app) for information on code not covered in this section.\n\n---\n**The `Backdrop.js` File:**\n```js\nfunction Backdrop(props) {\n  return \u003cdiv className='backdrop' onClick={props.onClick} /\u003e;\n}\n\nexport default Backdrop;\n```\n**Key Points:**\n* This component renders a `div` with a class of `backdrop`.\n    * `className` is the attribute used to assign CSS classes to elements in JSX. It is the equivalent of the `class` attribute in HTML.\n* It takes a prop called `onClick`, which is a function.\n* When the `Backdrop` is clicked, it calls the `onClick` function passed from the parent component.\n* The `Backdrop` component, in this example, is used to darken the screen background when a modal is displayed.\n\n---\n**The `Modal.js` File:**\n```js\nfunction Modal(props) {\n  return (\n    \u003cdiv className='modal'\u003e\n      \u003cp\u003e{props.text}\u003c/p\u003e\n      \u003cbutton className='btn btn--alt' onClick={props.onClose}\u003e\n        Cancel\n      \u003c/button\u003e\n      \u003cbutton className='btn' onClick={props.onClose}\u003e\n        Confirm\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default Modal;\n```\n**Key Points:**\n* Renders a `div` with a class of `modal`.\n* Contains a paragraph displaying the `text` prop, and two buttons (\"Cancel\" and \"Confirm\"), both of which execute the `onClose` function passed as a prop when clicked.\n\n---\n**The `Todo.js` File:**\n```js\nimport { useState } from 'react';\n\nimport Backdrop from './Backdrop';\nimport Modal from './Modal';\n\nfunction Todo(props) {\n  const [showModal, setShowModal] = useState();\n\n  function showModalHandler() {\n    setShowModal(true);\n  }\n\n  function closeModalHandler() {\n    setShowModal(false);\n  }\n\n  return (\n    \u003cdiv className='card'\u003e\n      \u003ch2\u003e{props.text}\u003c/h2\u003e\n      \u003cdiv className='actions'\u003e\n        \u003cbutton className='btn' onClick={showModalHandler}\u003e\n          Delete\n        \u003c/button\u003e\n      \u003c/div\u003e\n      {showModal \u0026\u0026 \u003cBackdrop onClick={closeModalHandler} /\u003e}\n      {showModal \u0026\u0026 \u003cModal text='Are you sure?' onClose={closeModalHandler} /\u003e}\n    \u003c/div\u003e\n  );\n}\n\nexport default Todo;\n```\n**Key Points:**\n* Imports `Modal` and `Backdrop` components.\n* Imports the React `usState` hook, which is used to manage and track state in functional components.\n* In this example, `usState` is used to manage the `showModal` variable.\n* Renders a `card` with a title (`props.text`) and a \"Delete\" button.\n* Clicking the \"Delete\" button triggers the `showModalHandler`, setting `showModal` to `true` with:\n    * `Backdrop` displayed - clicking it calls `closeModalHandler` to hide the modal. \n    * `Modal` displayed, asking the user for confirmation. Clicking either \"Cancel\" or \"Confirm\" also calls `closeModalHandler`.\n\n\n\u003e [!TIP]\n\u003e Check out the :file_folder: [state-management](/state-management/readme.md) section for more information on state usage in React applications.\n\n---\n**The `App.js` File:**\n```js\nimport Todo from './components/Todo';\n\nfunction App() {\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eReact Todo List\u003c/h1\u003e\n      \u003cTodo text='Learn React' /\u003e\n      \u003cTodo text='Learn React Hooks' /\u003e\n      \u003cTodo text='Learn React Router' /\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n* Imports the `Todo` component.\n* Renders the title \"React Todo List\" and a three `Todo` components.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## CSS Modules for Styling\n\n* [Basic CSS Files](#basic-css-files)\n* [Using CSS Modules](#using-css-modules)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [using-css-modules](/using-css-modules)\n\n### \u003ca name=\"basic-css-files\"\u003eBasic CSS Files\u003c/a\u003e\n\nIn React applications, a regular CSS file (`.css`) will apply styles globally to the entire component. \n\n:white_check_mark: Useful for global styles, resets, and shared styling.\n\n:rotating_light: Can lead to style conflicts if multiple components have the same class names.\n\n**\u003cins\u003eExample Case Using Basic CSS Styles:\u003c/ins\u003e**\n\nThe `Header.css` file:\n```css\n.header {\n    padding: 2rem;\n    display: flex;\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n    margin-bottom: 3rem;\n    text-align: center;\n}\n\n.header h1 {\n    margin: 0;\n    font-size: 1.5rem;\n}\n\n.header p {\n    margin: 0;\n}\n```\n\nThe `Header.js` file:\n```js\nimport React from 'react';\nimport './Header.css'; // Importing Basic CSS Stylesheet\n\nfunction Header() {\n  return (\n    \u003cheader className='header'\u003e\n      \u003ch1\u003eTop Books\u003c/h1\u003e\n      \u003cp\u003eCurated list of top-selling books\u003c/p\u003e\n    \u003c/header\u003e\n  );\n}\n\nexport default Header;\n```\n* :bulb: In React, the `className` property is used to assign a class name. \n  * This is equivalent to the `class` property in HTML elements.\n  * **Using basic CSS files**, a string defining the class name is used.\n\n---\n\n### \u003ca name=\"using-css-modules\"\u003eUsing CSS Modules\u003c/a\u003e\n\nCSS Modules scope CSS styles to a specific component, preventing style conflicts in your project.\n\n:white_check_mark: Styles are locally scoped to a specific component, which prevents class name collisions.\n\n:white_check_mark: Uses unique, automatically generated class names under the hood.\n\n:rotating_light: Requires a special import syntax.\n\n**\u003cins\u003eExample Case Using CSS Modules:\u003c/ins\u003e**\n\nThe `Books.module.css` file:\n```css\n.book {\n    display: flex;\n    flex-direction: column;\n    justify-content: flex-start;\n    align-items: center;\n    gap: 1rem;\n    background: linear-gradient(#1d3557, #324766);\n    padding: 1.5rem;\n    border-radius: 6px;\n    box-shadow: 0 2px 10px #455874;\n    width: 33%;\n    transition: all 0.2s\n}\n\n.book:hover {\n    transform: translateY(-2px);\n    transition: transform 0.2s;\n    box-shadow: 0 2px 20px #324766;\n}\n\n.book h2 {\n    margin: 0;\n    font-size: 1rem;\n    text-transform: uppercase;\n}\n\n.book p {\n    margin: 0;\n    text-align: center;\n    font-size: 0.95rem;\n}\n```\n\nThe `Books.js` file:\n```js\nimport React from 'react';\nimport styles from './Books.module.css'; // Importing CSS Module\n\nfunction Books(props) {\n  return props.items.map((item) =\u003e (\n    \u003cli className={styles.book} key={Math.random().toString()}\u003e\n      \u003ch2\u003e{item.title}\u003c/h2\u003e\n      \u003cp\u003e{item.description}\u003c/p\u003e\n    \u003c/li\u003e\n  ));\n}\n\nexport default Books;\n```\n* :bulb: In CSS Modules, when you import a `.module.css` file, the styles inside it are automatically converted into a JavaScript object where:\n  * **Keys** are the class names you defined in the CSS file.\n  * **Values** are unique, auto-generated class names to prevent conflicts.\n* **Using CSS module syntax**, the class name is defined between two curly braces (`{}`), accessing the `.book` class of the `styles` object (`className={styles.book}`).\n\n\u003e [!TIP]\n\u003e For more information about CSS Modules, check out the [documentation](https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/) published by the Create React App team.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## React Fragments\n\n* [Overview of React Fragments](#react-fragments-overview)\n* [Syntax of React Fragments](#react-fragments-syntax)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [react-fragments](/react-fragments)\n\n### \u003ca name=\"react-fragments-overview\"\u003eOverview of React Fragments\u003c/a\u003e\n\nIn React, a `Fragment` is a lightweight component that allows you to group multiple elements without adding extra nodes to the DOM. \n\nThis is useful when you need to return multiple elements from a component but don’t want to introduce unnecessary `\u003cdiv\u003e` wrappers.\n\n:white_check_mark: Helps keep the DOM cleaner and avoids unnecessary elements.\n\n:white_check_mark: Reduces DOM depth and improves rendering efficiency.\n\n:white_check_mark: Helps when rendering lists where an extra wrapper could interfere with styling.\n\n### \u003ca name=\"react-fragments-syntax\"\u003eSyntax of React Fragments\u003c/a\u003e\n\n#### Using the Explicit `React.Fragment` Syntax\n```js\nimport React from \"react\";\n\nfunction ExplicitEx() {\n    return (\n        \u003cReact.Fragment\u003e\n            \u003ch1\u003eHello\u003c/h1\u003e\n            \u003cp\u003eThis is an explicit React Fragment example.\u003c/p\u003e\n        \u003c/React.Fragment\u003e\n    );\n}\n\nexport default ExplicitEx;\n\n// Can also import \"Fragment\" from React, and use as: //\n// import React from \"react\";\nimport { Fragment } from \"react\";\n\nfunction ExplicitEx() {\n    return (\n        // \u003cReact.Fragment\u003e\n        //     \u003ch1\u003eHello\u003c/h1\u003e\n        //     \u003cp\u003eThis is an explicit React Fragment example.\u003c/p\u003e\n        // \u003c/React.Fragment\u003e\n        \u003cFragment\u003e\n            \u003ch1\u003eHello\u003c/h1\u003e\n            \u003cp\u003eThis is an explicit React Fragment example.\u003c/p\u003e\n        \u003c/Fragment\u003e\n    );\n}\n\nexport default ExplicitEx;\n```\n* Groups `\u003ch1\u003e` and `\u003cp\u003e` together without introducing an extra `\u003cdiv\u003e` in the DOM.\n\n---\n\n#### Using the Shorthand Syntax\n```js\nfunction ShorthandEx() {\n    return (\n        \u003c\u003e\n            \u003ch1\u003eHello\u003c/h1\u003e\n            \u003cp\u003eThis is an example of using the shorthand syntax for React Fragments.\u003c/p\u003e\n        \u003c/\u003e\n    );\n}\n\nexport default ShorthandEx;\n```\n* Shorthand offers simplicity, but **does not support attributes**.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Overview of React Hooks\n\n* [Overview](#react-hooks-overview)\n* [Rules of React Hooks](#react-hooks-rules)\n* [Built-in React Hooks](#react-hooks-built-in)\n* [Custom Hooks](#react-hooks-custom-hooks)\n\n---\n\n### \u003ca name=\"react-hooks-overview\"\u003eOverview\u003c/a\u003e\n\nReact Hooks are functions introduced in **React 16.8** that allow you to use React's state and lifecycle features in functional components, which were previously only available in class components. \n\nHooks simplify component logic, making it easier to reuse stateful logic without the need for complex patterns like higher-order components or render props.\n\n### \u003ca name=\"react-hooks-rules\"\u003eRules of React Hooks\u003c/a\u003e\nReact Hooks must follow these rules:\n1. They *must* be **called at the top level**: React hooks should not be called inside loops, conditions, or nested functions.\n2. They *must* be **called only in React functions**: Use hooks only in **functional components** or **custom hooks**, \u003cins\u003enot regular JavaScript functions\u003c/ins\u003e.\n\n### \u003ca name=\"react-hooks-built-in\"\u003eBuilt-in React Hooks\u003c/a\u003e\nReact provides several built-in hooks for development, grouped by purpose:\n\n* **[`useState`](#state-management)**: For managing state in functional components.\n```js\nconst [state, setState] = useState(initialState);\n```\n\n* **[`useEffect`](#react-side-effects)**: For managing side effects like data fetching or DOM updates.\n```js\nuseEffect(() =\u003e {\n  // Side effect logic here\n  return () =\u003e {\n    // Cleanup function (optional)\n  };\n}, [dependencies]);\n```\n\n* **`useContext`**: For consuming context without needing `Context.Consumer`.\n```js\nconst value = useContext(MyContext);\n```\n\n* **`useReducer`**: For managing complex state logic, similar to `redux` reducers.\n```js\nconst [state, dispatch] = useReducer(reducer, initialArg);\n```\n\n* **[`useCallback`](#performance-optimization)**: For memoizing functions to prevent unnecessary re-creation.\n```js\nconst memoizedCallback = useCallback(() =\u003e {\n  // Function logic\n}, [dependencies]);\n```\n\n* **[`useMemo`](#performance-optimization)**: For memoizing values to avoid expensive recalculations.\n```js\nconst memoizedValue = useMemo(() =\u003e computeExpensiveValue(a, b), [a, b]);\n```\n\n* **`useRef`**: Persist values across renders or directly manipulate DOM elements.\n```js\nconst ref = useRef(initialValue);\n```\n\n* **`useImperativeHandle`**: Customize what is exposed when using `ref` in parent components.\n```js\nuseImperativeHandle(ref, () =\u003e ({\n  customMethod() {\n    // Logic\n  },\n}));\n```\n\n* **`useLayoutEffect`**: Similar to `useEffect`, but runs synchronously after all DOM mutations.\n\n* **`useDebugValue`**: For debugging custom hooks.\n```js\nuseDebugValue(value);\n```\n\n\u003e [!TIP]\n\u003e Check out the React [documentation](https://react.dev/reference/react/hooks) for a complete list of built-in hooks.\n\n### \u003ca name=\"react-hooks-custom-hooks\"\u003eCustom Hooks\u003c/a\u003e\n\n* Custom hooks are user-defined hooks created by combining built-in hooks. They encapsulate reusable logic into a function prefixed with `use`.\n```js\nfunction useFetch(url) {\n  const [data, setData] = useState(null);\n\n  useEffect(() =\u003e {\n    fetch(url)\n      .then((res) =\u003e res.json())\n      .then((data) =\u003e setData(data));\n  }, [url]);\n\n  return data;\n}\n```\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## State Management\n\u003eFirst look at using the built-in React hook `useState` for state management.\n\n* [State Management Overview](#state-management-overview)\n* [Example With useState](#example-with-usestate)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [state-management](/state-management)\n\n### State Management Overview\n\n**Overview:**\n\nThe `useState` hook in React is used to manage and track state in **functional components**.\n\nThis hook provides a way to store values that can change over time and trigger re-renders when those values change.\n\n**Syntax:**\n```js\nconst [state, setState] = useState(initialValue);\n```\n* `state`: The current value of the state.\n* `setState`: A function to update the state value.\n* `initialValue`: The initial value of the state.\n\n### Example With `useState`\n\n**The `StateManagementEx.js` File:**\n```js\nimport { useState } from 'react';\n\nfunction StateManagementEx() {\n    const [count, setCount] = useState(0);\n\n    function addHandler() {\n        setCount(count + 1);\n    }\n\n    function subtractHandler() {\n        setCount(count - 1);\n    }\n\n    return (\n        \u003cdiv\u003e\n            \u003ch2\u003eCounter Example\u003c/h2\u003e\n            \u003cp\u003eCurrent Count: {count}\u003c/p\u003e\n            \u003cbutton onClick={addHandler}\u003eAdd 1\u003c/button\u003e\n            \u003cbutton onClick={subtractHandler}\u003eSubtract 1\u003c/button\u003e\n        \u003c/div\u003e\n    )\n\n}\nexport default StateManagementEx;\n```\n* `useState(0)` initializes count variable set to `0`.\n* The `setCount` function is used to update the `count` state and triggers a re-render to reflect the updated value.\n* `addHandler` is passed to the `onClick` event handler and *increases* the count by 1 when the \"Add 1\" button is clicked.\n* `subtractHandler` is passed to the `onClick` event handler and *decreases* the count by 1 when the \"Subtract 1\" button is clicked.\n  * The `onClick` event handler allows execution of a function when a user clicks on the element.\n\n---\n\n**The `App.js` File:**\n```js\nimport StateManagementEx from \"./components/StateManagementEx\";\n\nfunction App() {\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eState Management\u003c/h1\u003e\n      \u003cStateManagementEx /\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n* Renders the `StateManagementEx` component.\n\n\u003e [!TIP]\n\u003e Check out the complete React [documentation](https://react.dev/reference/react/useState) on the built-in `useState` hook.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## React Side Effects\n\u003eA look at managing side effects with the `useEffect` hook.\n\n* [Side Effects Overview](#side-effects-overview)\n* [Understanding Component Lifecycle](#side-effects-component-lifecycle)\n* [Timer Example With useEffect](#side-effects-example)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [react-side-effects](/react-side-effects)\n\n---\n\n### \u003ca name=\"side-effects-overview\"\u003eSide Effects Overview\u003c/a\u003e\n\n**Overview:**\n\n`useEffect` is a built-in React Hook that allows you to perform side effects in functional components. \n\nIt runs after the component renders and can be used for tasks such as:\n* Fetching data from an API\n* Subscribing to events\n* Updating the DOM\n* Managing timers\n\n**Syntax:**\n```js\nuseEffect(() =\u003e {\n  // Side effect logic here\n  return () =\u003e {\n    // Cleanup function (optional)\n  };\n}, [dependencies]);\n```\n`useEffect` takes two arguments:\n* `() =\u003e {}`: The first argument is a function that runs the effect.\n* `[dependencies]`: The second argument is an array of dependencies that controls when the effect runs. This can be:\n  * `[]` (empty array) - Runs only once after the first render.\n  * No dependency array - Runs after every render.\n  * `[someValue]` → Runs when `someValue` changes.\n\n---\n\n### \u003ca name=\"side-effects-component-lifecycle\"\u003eUnderstanding Component Lifecycle\u003c/a\u003e\n\nIn React, you often here the terms **mounts** or **unmounts** with relation to components. These refer to the lifecycle of a component - when it is added (mount) to or removed (unmount) from the **DOM (Document Object Model)**.\n\n**A Closer Look at \"Mounting\":**\n\nWhen a component mounts, it means:\n* The component is being **created and inserted** into the DOM.\n* React renders the component for the first time.\n* The `useEffect` hook, with an empty dependency array, runs once.\n\nExamples of component mounting include:\n* A component that is added to the UI.\n* A component conditionally rendered based on state.\n* A user navigates to a route where the component appears.\n\n**A Closer Look at \"Unmounting\":**\n\nWhen a component unmounts, it means:\n* The component is **removed** from the DOM.\n* Any side effects (event listeners, timers, etc.) should be cleaned up to prevent memory leaks.\n* The cleanup function in `useEffect` runs before unmounting.\n\nExamples of component unmounting include:\n* The user navigates away from a route containing the component.\n* The component is conditionally removed.\n* A parent component re-renders, causing the child component to be removed.\n\n**Example Case of \"Mounting\" and \"Unmounting\":**\n```js\nuseEffect(() =\u003e {\n    console.log('The \"Mount\" component has been mounted!');\n\n    return () =\u003e {\n        console.log('The \"Mount\" component has been unmounted!');\n    };\n}, []); // Empty dependency array -\u003e Runs once on mount\n```\n\n---\n\n### \u003ca name=\"side-effects-example\"\u003eExample With useEffect\u003c/a\u003e\n\n**The `Counter.js` File:**\n```js\nimport React, { useState, useEffect } from \"react\";\n\nfunction Counter() {\n    const [count, setCount] = useState(0);\n\n    // Effect 1: Start a time when the component mounts\n    useEffect(() =\u003e {\n        const interval = setInterval(() =\u003e {\n            setCount(prev =\u003e prev + 1);\n        }, 1000);\n\n        // Cleanup function to stop the interval when component unmounts\n        return () =\u003e {\n            clearInterval(interval);\n        };\n    }, []); // Runs only once when the component mounts\n\n    // Effect 2: Update the document title whenever count changes\n    useEffect(() =\u003e {\n        document.title = `Count: ${count}`;\n    }, [count]); // Runs only when count changes\n\n    return (\n        \u003cdiv\u003e\n            \u003ch2\u003eCounter: {count}\u003c/h2\u003e\n            \u003cbutton onClick={() =\u003e setCount(0)}\u003eReset\u003c/button\u003e\n        \u003c/div\u003e\n    );\n}\n\nexport default Counter;\n```\n\n**The `App.js` File:**\n```js\nimport React, { useEffect } from \"react\";\nimport Counter from \"./components/Counter\";\n\nfunction App() {\n  // Effect 3: Clear any initial console logs when the component mounts\n  useEffect(() =\u003e {\n    console.clear();\n  }, []);\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eReact Side Effects - Timer Example\u003c/h1\u003e\n      \u003cCounter /\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n\n\u003e [!TIP]\n\u003e Check out the complete React [documentation](https://react.dev/reference/react/useEffect) on the built-in `useEffect` hook.\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Performance Optimization\n\u003eReact project demonstrating the use of `useMemo` and `React.memo`, as well as `useCallback` for performance optimization.\n\n* [Default Rendering Behavior](#performance-optimization-default-behavior)\n* [Overview of Optimizations](#performance-optimization-overview)\n* [Key Differences](#performance-optimization-key-differences)\n* [Understanding Memoization](#performance-optimization-memoization)\n* [Understanding Shallow Comparison](#performance-optimization-shallow-comparison)\n* [Basic Syntax of useMemo](#performance-optimization-basic-syntax-of-usememo)\n* [Basic Syntax of useCallback](#performance-optimization-basic-syntax-of-usecallback)\n* [Basic Syntax of React.memo](#performance-optimization-basic-syntax-of-reactmemo)\n* [Changes to Default Rendering Behavior](#performance-optimization-default-behavior-changes)\n* [Project Structure](#performance-optimization-project-structure)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [performance-optimization](/performance-optimization)\n\n### \u003ca name=\"performance-optimization-default-behavior\"\u003eDefault Rendering Behavior\u003c/a\u003e\n\nBy default, React will re-render a component when:\n1. **Its state changes** → When you call `setState`, the component and its children re-render.\n2. **Its props change** → If a parent component passes new props, the child component re-renders.\n3. **Its parent re-renders** → If a parent component re-renders (even without changing props), React re-renders its children.\n\nThis default re-rendering behavior ensures that the UI stays in sync with the application state, but this often leads to **unnecessary re-renders that \u003cins\u003enegatively impact performance\u003c/ins\u003e**.\n\nThat is where `useMemo`, `useCallback`, and `React.memo` come into place. These optimizations, provided by React, help reduce unnecessary re-renders and improve application performance.\n\n### \u003ca name=\"performance-optimization-overview\"\u003eOverview of Optimizations\u003c/a\u003e\n\n#### `useMemo`\nThe `useMemo` React Hook is used to optimize performance by **[memoizing](#performance-optimization-memoization)** (also known as **[caching](#caching)**) the result of a function or computation, so that it is only recalculated when its dependencies change. This prevents expensive computations from running unnecessarily during every render.\n\n\u003e [!TIP]\n\u003e Check out the complete React [documentation](https://react.dev/reference/react/useMemo) on the built-in `useMemo` hook.\n\n#### `React.memo`\nIn React, `React.memo` is a **higher-order component (HOC)** provided by React, specifically designed to automatically memoize functional components. When a component is wrapped with `React.memo`, it will re-render only if its props have changed.\n\n#### `useCallback`\n`useCallback` is a React Hook used to memoize callback functions. It ensures that a function reference remains the same across renders unless its dependencies change. \n\nThis optimization is useful when passing callbacks to child components to prevent re-creations of functions during component re-renders.\n\nIf you pass a new function reference (even with the same logic) as a prop, `React.memo` will trigger a re-render. `useCallback` ensures that the function reference stays the same across renders, **working effectively with `React.memo`**.\n\n\u003e [!TIP]\n\u003e Check out the complete React [documentation](https://react.dev/reference/react/useCallback) on the built-in `useCallback` hook.\n\n### \u003ca name=\"performance-optimization-key-differences\"\u003eKey Differences\u003c/a\u003e\n| Feature           | `React.memo`          | `useMemo`         | `useCallback`     |\n| ----------------- | --------------------- | ----------------- | ----------------- |\n| Functionality     | Prevents a component from re-rendering based on its props. | Caches the result of a function call based on its dependencies. | Caches a function definition so it does not get re-created on every render. |\n| Usage             | Used to wrap a functional component. | Called inside a functional component to memoize a specific calculation. | Wraps a function inside a functional component. | \n| Comparison        | Performs a [shallow comparison](#performance-optimization-shallow-comparison) of props by default to determine if a re-render is needed. | Explicitly defines dependencies in an array to control when the calculation is re-run. | Explicitly defines dependencies in an array to determine when the function should be re-created. |\n\n`React.memo` focuses on optimizing component rendering, while `useMemo` optimizes specific calculations within a component. \n\n**Use Case for Each:**\n\n* Use `React.memo` when you have a component that is rendered frequently and its rendering logic is relatively simple but depends heavily on its props. \n* Use `useMemo` when you have a computationally expensive calculation within a component that needs to be cached and only re-calculated when its dependencies change. \n* Use `useCallback`: \n    * When functions are passed as props, preventing unnecessary child re-renders.\n    * When passing functions as props to child components wrapped with `React.memo`.\n    * When functions are used as dependencies in `useEffect` or `useMemo` to avoid triggering unintended re-runs.\n\n### \u003ca name=\"performance-optimization-memoization\"\u003eUnderstanding Memoization\u003c/a\u003e\n\n**\u003ca name=\"caching\"\u003eCaching\u003c/a\u003e is a technique that allows us to store a copy of a given resource and serve it back when it is requested.**\n\nMemoization is a technique used to optimize the performance of functions by **caching** the results of expensive function calls and reusing them when the same inputs occur again.\n\nIn React applications, **memoization** helps avoid redundant rendering of components, ultimately leading to a smoother user experience.\n\n### \u003ca name=\"performance-optimization-shallow-comparison\"\u003eUnderstanding Shallow Comparison\u003c/a\u003e\n\nShallow comparison refers to a comparison of **references only**, not the actual content of the objects. If two variables reference the same object in memory, the shallow comparison will consider them equal. It does not go into nested objects or arrays to check for equality.\n\n```js\nconst array1 = [1, 2, 3];\nconst array2 = [1, 2, 3];\nconst array3 = array1; // Points to the same memory reference as array1\n\nconsole.log(array1 === array2); // false (different references)\nconsole.log(array1 === array3); // true (same reference)\n```\n\n### \u003ca name=\"performance-optimization-basic-syntax-of-usememo\"\u003eBasic Syntax of useMemo\u003c/a\u003e\n```js\nconst cachedValue = useMemo(calculateValue, dependencies)\n```\n* `calculateValue`: The function calculating the value that you want to cache.\n    * React will call this function during the initial render. \n    * On next renders, React will return the same value if the `dependencies` have not changed.\n* `dependencies`:\n    * List of all **reactive** values referenced inside of the calculateValue code. \n    * This include props, state, and all the variables and functions declared directly inside your component body.\n\n### \u003ca name=\"performance-optimization-basic-syntax-of-usecallback\"\u003eBasic Syntax of useCallback\u003c/a\u003e\n```js\nconst memoizedCallback = useCallback(\n  () =\u003e {\n    // Callback Function (Your callback logic here)\n  },\n  [dependencies] // Dependency Array (function recreation if these change)\n);\n```\n* Callback Function - The function you want to memoize.\n* Dependency Array - Determines when the memoized function should be recreated.\n* A memoized version of the function that only changes if the dependencies change will be returned.\n\n### \u003ca name=\"performance-optimization-basic-syntax-of-reactmemo\"\u003eBasic Syntax of React.memo\u003c/a\u003e\n\nThere are multiple ways to use `React.memo`, here are a few examples:\n\n**Example 1:**\n\nThe `React.memo` function is used to wrap the component and then export:\n```js\nimport React from 'react';\n\nconst ComponentOne = (props) =\u003e {\n   /* component code */\n};\n\nexport default React.memo(ComponentOne);\n```\n\n**Example 2:**\n\nThe `memo()` function is used to wrap a new variable and then store the memoized component to be exported:\n```js\nimport { memo } from \"react\";\n\nconst ComponentTwo = (props) =\u003e {  \n  /* render using props */  \n};\n\nexport const MemoComponent = memo(ComponentTwo);\n```\n\n**Example 3:**\n\nThe `memo()` function is used to wrap the entire component:\n```js\nimport { memo } from \"react\";\n\nconst ComponentThree = memo((props) =\u003e {  \n   /* component code */  \n});\n\nexport default ComponentThree;\n```\n\n### \u003ca name=\"performance-optimization-default-behavior-changes\"\u003eChanges to Default Rendering Behavior\u003c/a\u003e\n| Feature               | Default Behavior              | `React.memo`              | `useMemo`             | `useCallback`             |\n| --------------------- | ----------------------------- | ------------------------- | --------------------- | ------------------------- |\n| State Change          | Component always re-renders   | No effect                 | No effect             | No effect                 |\n| Props Are the Same    | Component re-renders          | :white_check_mark: Prevents re-render | No effect | No effect                 |\n| Parent Re-renders     | Child re-renders              | :white_check_mark: Prevents re-render | No effect | No effect                 |\n| Expensive Computations | Always recalculates          | No effect | :white_check_mark: Prevents recalculation | No effect             |\n| Functions as Props    | New function created on every render | No effect | No effect | :white_check_mark: Prevents re-creation        |\n\n### \u003ca name=\"performance-optimization-project-structure\"\u003eProject Structure\u003c/a\u003e\n```\nperformance-optimization/\n├── public/\n    ├── index.html\n    ├── favicon.ico\n    ├── manifest.json\n    └── robots.txt\n├── src/\n    ├── components/\n    |   ├── Demo/\n    |   |   ├── DemoList.js\n    |   |   ├── DemoList.module.css\n    |   ├── UI/\n    |   |   ├── Button/\n    |   |   |   ├── Button.js\n    |   |   |   ├── Button.module.css\n    ├── App.css\n    ├── App.js\n    ├── index.css\n    ├── index.js\n├── .gitignore\n├── package.json\n├── readme.md\n```\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## Sending HTTP Requests\n\n* [Overview of HTTP Requests in React](#making-http-requests-overview)\n* [Understanding Asynchronous Requests in JavaScript](#making-http-requests-asynchronous-ops)\n* [Making a Request to The Star Wars API](#making-http-requests-to-star-wars-api)\n\n\u003e [!NOTE]\n\u003e All examples in this section can be found in :file_folder: [making-http-requests](/making-http-requests)\n\n### \u003ca name=\"making-http-requests-overview\"\u003eOverview of HTTP Requests in React\u003c/a\u003e\n\nIn React applications, HTTP requests are commonly made by using JavaScript's `fetch()` API or third-party libraries. \n\nThese requests are usually performed in lifecycle methods, such as `useEffect` or `useCallback` to fetch data from an external API when a component mounts or when triggered by user actions.\n\n---\n\n### \u003ca name=\"making-http-requests-asynchronous-ops\"\u003eUnderstanding Asynchronous Requests in JavaScript\u003c/a\u003e\n\nIn JavaScript, **asynchronous operations** allow code execution without blocking the main thread, enabling tasks like fetching data, handling user interactions, or waiting for a timer without stopping the execution of other code.\n\nJavaScript is **single-threaded**, meaning it can only execute one operation at a time. Without asynchronous programming, JavaScript would freeze whenever a long-running task is executed.\n\nAsynchronous operations include **callbacks**, **promises**, and **async/await** mechanisms.\n\nThe `async` and `await` keywords in JavaScript are used to work with these operations, particularly with Promises. They allow us to write asynchronous code that looks and behaves more like synchronous code, making it easier to read and manage.\n\n1. **Callbacks (Old Approach - Rarely Used and Not Recommended Anymore)**\n* Before Promises, callbacks were the primary way to handle asynchronous operations.\n```js\nfunction fetchData(callback) {\n    setTimeout(() =\u003e {\n        callback(\"Received\");\n    }, 2000);\n}\n\nfetchData((result) =\u003e {\n    console.log(result);\n});\n```\n* Biggest issue that came with callbacks was **Callback Hell** where nesting multiple callbacks led to unreadable code.\n\n---\n\n1. **Promises (More Modern Approach)**\n* A Promise represents a value that will be available in the future. It has three states: **pending**, **fulfilled**, and **rejected**.\n```js\n// Fetching a JSON file\nfunction fetchData() {\n  fetch('./movies.json').then((response) =\u003e {\n    return response.json();\n  }).then((data) =\u003e {\n    console.log(data);\n  });\n}\n```\n* Promises resolved the issue of callback hell.\n\n---\n\n3. **Async/Await (Modern Syntax for Promises)**\n* The `async` and `await` keywords simplify working with Promises.\n```js\nasync function getUsers() {\n  const res = await fetch('https://jsonplaceholder.typicode.com/users');\n  const data = await res.json();\n  console.log(data);\n}\n\nasync function fetchPost() {\n    try {\n        const response = await fetch(\"https://jsonplaceholder.typicode.com/posts\");\n        const data = await response.json();\n        console.log(data);\n    } catch (error) {\n        console.error(\"Error:\", error);\n    }\n}\n```\n* Using async/await is more readable then `.then()` chaining.\n* Provides a *synchronous-like* structure for easier debugging and better error handling.\n\n#### Summary of Asynchronous Operations\n| Feature           | Callbacks            | Promises                    | Async/Await             |\n| ----------------- | -------------------- | --------------------------- | ----------------------- |\n| Readability       | Poor (callback hell) | Better (`.then()` chaining) | Best (synchronous-like) |\n| Error Handling    | Difficult            | Better (`.catch()`)         | Best (`try...catch`)    |\n| Nesting Issues    | Yes                  | No                          | No                      |\n| Flexibility       | Low                  | Medium                      | High                    |\n\n---\n\n### \u003ca name=\"making-http-requests-to-star-wars-api\"\u003eMaking a Request to [The Star Wars API](https://swapi.dev/)\u003c/a\u003e\n\n\u003e [!NOTE]\n\u003e All Star Wars data at [https://swapi.dev/](https://swapi.dev/) :arrow_upper_right:\n\n#### The `App.js` File\n\n**\u003cins\u003eImporting Component Dependencies:\u003c/ins\u003e**\n```js\nimport React, { useState, useEffect, useCallback } from 'react';\nimport MoviesList from './components/MoviesList';\nimport './App.css';\n```\n\n**\u003cins\u003eDefining Component State:\u003c/ins\u003e**\n```js\nconst [movies, setMovies] = useState([]);\nconst [isLoading, setIsLoading] = useState(false);\nconst [error, setError] = useState(null);\n```\n* `movies` will store the fetched movie data - initially set to an empty array (`[]`).\n* `isLoading` will track the status of data being fetched - initially set to `false`.\n* `error` will store any errors that occur during fetching - initially set to `null`.\n\n**\u003cins\u003eDefining the Movie Fetch Handler:\u003c/ins\u003e**\n```js\nconst fetchMoviesHandler = useCallback(async () =\u003e {\n    setIsLoading(true);\n    setError(null);\n    try {\n      const response = await fetch('https://swapi.dev/api/films/');\n\n      if (!response.ok) {\n        throw new Error(response.status + ' : Something went wrong...');\n      }\n\n      const data = await response.json();\n\n      const transformedMovies = data.results.map((movieData) =\u003e {\n        return {\n          id: movieData.episode_id,\n          title: movieData.title,\n          openingText: movieData.opening_crawl,\n          releaseDate: movieData.release_date,\n        };\n      });\n      setMovies(transformedMovies);\n    } catch (error) {\n      setError(error.message);\n    }\n    setIsLoading(false);\n}, []);\n```\n**Looking at `useCallback`**\n```js\nconst fetchMoviesHandler = useCallback(async () =\u003e { ... }, []);\n```\n* The dependency array in this function is empty (`[]`), which means the function is created **only once** when the component first renders.\n\n**Updating State Variables**\n```js\nsetIsLoading(true);\nsetError(null);\n```\n* `setIsLoading(true)`: Data starts loading - `isLoading` state is set to `true`.\n* `setError(null)`: This resets the error state to its initial state, if any previous errors occurred.\n\n**The `try...catch` block**\n```js\ntry {\n      const response = await fetch('https://swapi.dev/api/films/');\n    ...\n}\n```\n* Fetches data from the external **Star Wars API**.\n* `await` ensures the function waits for the API response before continuing execution.\n* What is returned from the API call is stored in the `response` variable.\n\n```js\nif (!response.ok) {\n  throw new Error(response.status + ' : Something went wrong...');\n}\n```\n* Checks if the response returned is of the status code **4xx** or **5xx**, such as **404 Not Found** or **500 Internal Server Error**.\n* If the status is not *OK*, then a new error is thrown with a message including the HTTP status code.\n\n```js\nconst data = await response.json();\n```\n* Parses the response by converting from JSON format into a JavaScript object.\n* `await` ensures it waits until the JSON is completely parsed.\n\n```js\nconst transformedMovies = data.results.map((movieData) =\u003e {\n  return {\n    id: movieData.episode_id,\n    title: movieData.title,\n    openingText: movieData.opening_crawl,\n    releaseDate: movieData.release_date,\n  };\n});\nsetMovies(transformedMovies);\n```\n* The Star Wars API returns an array of movie objects inside `data.results`.\n* `.map()` is used to loop through each movie and extracts only the needed properties.\n* `setMovies(transformedMovies)` updates the state, triggering a re-render to display the new movie list.\n\n```js\ncatch (error) {\n  setError(error.message);\n}\n```\n* If an error occurs anywhere inside the `try` block, execution jumps to the `catch` block, where the error message is stored in React state (`setError(error.message)`).\n\n**Final Cleanup**\n```js\nsetIsLoading(false);\n```\n* Sets the loading state back to false, ensuring it is done whether the fetch was successful or an error occurred.\n\n**\u003cins\u003eFetching Data on Component Mount:\u003c/ins\u003e**\n```js\nuseEffect(() =\u003e {\n  fetchMoviesHandler();\n}, [fetchMoviesHandler]);\n```\n* Ensures that `fetchMoviesHandler` runs automatically when the component first mounts.\n* Since `fetchMoviesHandler` is wrapped with `useCallback`, React ensures it does not cause unnecessary re-renders.\n\n**\u003cins\u003eUI State Handling:\u003c/ins\u003e**\n```js\nlet content = \u003cp\u003eNo movies found.\u003c/p\u003e;\n\nif (movies.length \u003e 0) {\n  content = \u003cMoviesList movies={movies} /\u003e;\n}\n\nif (error) {\n  content = \u003cp\u003e{error}\u003c/p\u003e;\n}\n\nif (isLoading) {\n  content = \u003cp\u003eLoading...\u003c/p\u003e;\n}\n```\n* Renders a different UI based on status of state:\n  * Shows \"No movies found.\" if no movies are available.\n  * Displays the `MoviesList` component if movies exist (passing the `movies` as prop).\n  * Shows an error message if fetching fails.\n  * Displays \"Loading...\" while the request is in progress.\n\n**\u003cins\u003eRendering the UI:\u003c/ins\u003e**\n```js\nreturn (\n  \u003cReact.Fragment\u003e\n    \u003csection\u003e\n      \u003cbutton onClick={fetchMoviesHandler}\u003eFind Movies\u003c/button\u003e\n    \u003c/section\u003e\n    \u003csection\u003e{content}\u003c/section\u003e\n  \u003c/React.Fragment\u003e\n);\n```\n* A button manually triggers `fetchMoviesHandler`.\n* Dynamically displays the updates of `content` based on `movies`, `isLoading`, and `error`.\n\n**\u003cins\u003eExporting the Component:\u003c/ins\u003e**\n```js\nexport default App;\n```\n* Makes `App` available for use in `index.js` (or any other part of the app).\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n\n## All React Demo Projects\n\n### Fundamentals\n| Project | Description | Link |\n|---------|-------------|------|\n| Introduction Project | Basic introduction to React concepts | [:link::file_folder:](/introduction-project) |\n| Key React Concepts | UI for displaying key React concepts | [:link::file_folder:](/key-react-concepts) |\n| Base React App | Template structure for React projects | [:link::file_folder:](/base-react-app) |\n| React Fragments | Using React fragments for cleaner JSX | [:link::file_folder:](/react-fragments) |\n| Function vs Class Components | Comparing component styles | [:link::file_folder:](/function-class-components) |\n| Class-Based Components | Working with class components and lifecycle | [:link::file_folder:](/class-based-components) |\n\n### Styling\n| Project | Description | Link |\n|---------|-------------|------|\n| Using CSS Modules | Scoped styling with CSS Modules | [:link::file_folder:](/using-css-modules) |\n| Hoverboard Effect | Fun interactive hoverboard effect | [:link::file_folder:](/hoverboard-effect) |\n| Login Page UI | Login page with input validation | [:link::file_folder:](/login-page-ui) |\n| Animating React Apps | Adding animations to React components | [:link::file_folder:](/animating-react-apps) |\n\n### State \u0026 Data\n| Project | Description | Link |\n|---------|-------------|------|\n| State Management | Managing component and application state | [:link::file_folder:](/state-management) |\n| Course Goal | Adding course goals to a list | [:link::file_folder:](/course-goal) |\n| Add User | Adding users to a list | [:link::file_folder:](/add-user) |\n| Investment Calculator | Calculating and displaying investments | [:link::file_folder:](/investment-calculator) |\n| Expense Tracker | App for keeping track of expenses | [:link::file_folder:](/expense-tracker) |\n| Forms and User Input | Handling forms and validation | [:link::file_folder:](/forms-and-user-input) |\n\n### Hooks\n| Project | Description | Link |\n|---------|-------------|------|\n| React Side Effects | Using useEffect for side effects | [:link::file_folder:](/react-side-effects) |\n| Custom React Hooks | Building reusable custom hooks | [:link::file_folder:](/custom-react-hooks) |\n| Custom React Hooks Pt. 2 | Advanced custom hook patterns | [:link::file_folder:](/custom-react-hooks-pt-2) |\n\n### HTTP \u0026 APIs\n| Project | Description | Link |\n|---------|-------------|------|\n| Sending HTTP Requests | Fetching data from APIs | [:link::file_folder:](/sending-http-requests) |\n| HTTP Requests Pt. 2 | Advanced HTTP patterns | [:link::file_folder:](/http-requests-pt-2) |\n| Pokemon Cards | Fetching and displaying Pokemon data | [:link::file_folder:](/pokemon-cards) |\n| Book Finder | Searching books via Open Library API | [:link::file_folder:](/book-finder) |\n| Book Finder with Router | Book search with React Router | [:link::file_folder:](/book-finder-with-router) |\n\n### Routing\n| Project | Description | Link |\n|---------|-------------|------|\n| React Router | Introduction to React Router | [:link::file_folder:](/react-router) |\n| Advanced React Router | Complex routing patterns | [:link::file_folder:](/adv-react-router-project) |\n| Adding Authentication | Auth with protected routes | [:link::file_folder:](/adding-authentication) |\n\n### State Management (Redux)\n| Project | Description | Link |\n|---------|-------------|------|\n| Redux Basics | Introduction to Redux | [:link::file_folder:](/redux-basics) |\n| Redux React Project | Integrating Redux with React | [:link::file_folder:](/redux-react-project) |\n| Advanced Redux | Advanced Redux patterns and async | [:link::file_folder:](/advanced-redux) |\n\n### Full Applications\n| Project | Description | Link |\n|---------|-------------|------|\n| Food Order App | Online food ordering cart | [:link::file_folder:](/food-order-app) |\n| Adding HTTP to Food Order | Food order app with backend | [:link::file_folder:](/adding-http-to-food-order-app) |\n\n### Performance \u0026 Testing\n| Project | Description | Link |\n|---------|-------------|------|\n| Performance Optimization | React performance techniques | [:link::file_folder:](/performance-optimization) |\n| Optimization Techniques | Advanced optimization patterns | [:link::file_folder:](/optimization-techniques) |\n| Testing with Jest | Unit and integration testing | [:link::file_folder:](/testing-with-jest) |\n\n### Deployment \u0026 Next.js\n| Project | Description | Link |\n|---------|-------------|------|\n| Deploying React Apps | Deployment strategies | [:link::file_folder:](/deploying-react-apps) |\n| Next.js Dummy News | Server-side rendering with Next.js | [:link::file_folder:](/nextjs-dummy-news-project) |\n| Next.js Meetup App | Full Next.js application | [:link::file_folder:](/nextjs-meetup-app) |\n\n\u003ckbd\u003e \u003cbr\u003e [Back to Top](#table-of-contents) \u003cbr\u003e \u003c/kbd\u003e\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsidneyshafer%2Fcomplete-react-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsidneyshafer%2Fcomplete-react-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsidneyshafer%2Fcomplete-react-guide/lists"}