{"id":13459253,"url":"https://github.com/learning-zone/react-basics","last_synced_at":"2025-05-15T12:04:44.035Z","repository":{"id":37812623,"uuid":"239674976","full_name":"learning-zone/react-basics","owner":"learning-zone","description":"React Basics ( v18.x )","archived":false,"fork":false,"pushed_at":"2024-08-07T07:43:48.000Z","size":14567,"stargazers_count":1562,"open_issues_count":0,"forks_count":430,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-04-14T19:59:33.812Z","etag":null,"topics":["react","react-coding-challenges","react-hooks","react-interview-questions","react-projects","react-router","react-unit-testing","redux","redux-form","redux-saga","redux-thunk"],"latest_commit_sha":null,"homepage":"https://learning-zone.github.io/react-basics/","language":null,"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/learning-zone.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}},"created_at":"2020-02-11T04:23:02.000Z","updated_at":"2025-04-13T09:56:52.000Z","dependencies_parsed_at":"2024-01-13T17:55:26.190Z","dependency_job_id":"11a909b1-5b22-4deb-9dd9-eefb689c5cc9","html_url":"https://github.com/learning-zone/react-basics","commit_stats":{"total_commits":1474,"total_committers":8,"mean_commits":184.25,"dds":"0.011533242876526462","last_synced_commit":"6a96541f5519af85e7e2648e4d041d2075535614"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Freact-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Freact-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Freact-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Freact-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learning-zone","download_url":"https://codeload.github.com/learning-zone/react-basics/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254337612,"owners_count":22054253,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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","react-coding-challenges","react-hooks","react-interview-questions","react-projects","react-router","react-unit-testing","redux","redux-form","redux-saga","redux-thunk"],"created_at":"2024-07-31T09:01:12.573Z","updated_at":"2025-05-15T12:04:39.020Z","avatar_url":"https://github.com/learning-zone.png","language":null,"readme":"# React Basics\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily ♡ welcome.*\n\n\u003cbr/\u003e\n\n## Related Topics\n\n* *[HTML Basics](https://github.com/learning-zone/html-basics)*\n* *[CSS Basics](https://github.com/learning-zone/css-basics)*\n* *[JavaScript Basics](https://github.com/learning-zone/javascript-basics)*\n* *[React Coding Practice](react-coding-practice.md)*\n* *[React Quick Reference](react-quick-reference.md)*\n* *[Redux Quick Reference](redux-quick-reference.md)*\n* *[Jest Quick Reference](jest-quick-reference.md)*\n* *[React Best Practices](best-practices.md)*\n* *[React Unit Testing](https://github.com/learning-zone/react-unit-testing)*\n* *[React Project - ToDo App](https://github.com/learning-zone/react-todo-app)*\n* *[React Project - My Store App](https://github.com/learning-zone/my-store-app)*\n\n\u003cbr/\u003e\n\n## Table of Contents\n\n* React\n  * [Introduction](#-1-introduction)\n  * [React Setup](#-2-react-setup)\n  * [React JSX](#-3-react-jsx)\n  * [React Components](#-4-react-components)\n    * [Functional Components](#-41-functional-components)\n    * [Class Components](#-42-class-components)\n      * [React Lifecycle](#-421-react-lifecycle)\n    * [Pure Components](#-43-pure-components)\n    * [Higher Order Components](#-44-higher-order-components)\n    * [Lazy Loading](#-45-lazy-loading)\n  * [React Props](#-5-react-props)\n  * [React State](#-6-react-state)\n  * [React Events](#-7-react-events)\n  * [React Lists](#-8-react-lists)\n  * [React RESTful API](#-9-react-restful-api)\n  * [React Forms](#-10-react-forms)\n  * [React Hooks](#-11-react-hooks)\n  * [React Context](#-12-react-context)\n  * [React Router](#-13-react-router)\n  * [React Error Boundaries](#-14-react-error-boundaries)\n  * [React Refs](#-15-react-refs)\n  * [React Composition](#-16-react-composition)\n  * [React CSS Styling](#-17-react-css-styling)\n  * [React Internationalization](#-18-react-internationalization)\n  * [React Testing](#-19-react-testing)\n  * [React Miscellaneous](#-20-react-miscellaneous)\n\n* Redux\n  * [Redux Overview](#-1-redux-overview)\n  * [Redux Setup](#-2-redux-setup)\n  * [Redux Data Flow](#-3-redux-data-flow)\n  * [Redux Store](#-4-redux-store)\n  * [Redux Actions](#-5-redux-actions)\n  * [Redux Reducers](#-6-redux-reducers)\n  * [Redux Middleware](#-7-redux-middleware)\n  * [Redux Forms](#-8-redux-forms)\n  * [Redux Miscellaneous](#-9-redux-miscellaneous)\n\n\u003cbr/\u003e\n\n## # 1. INTRODUCTION\n\n\u003cbr/\u003e\n\n## Q. What is React.js?\n\nReact is a JavaScript library created for building fast and interactive user interfaces for web and mobile applications. It is an open-source, component-based, front-end library responsible only for the application view layer.\n\nThe main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. It uses virtual DOM (JavaScript object), which improves the performance of the app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on the client and server-side as well as with other frameworks. It uses component and data patterns that improve readability and helps to maintain larger apps.\n\n**Reference:**\n\n* *[https://reactjs.org/tutorial/tutorial.html](https://reactjs.org/tutorial/tutorial.html)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How React works?\n\nReact implements a virtual DOM that is basically a DOM tree representation in Javascript. So when it needs to read or write to the DOM, it will use the virtual representation of it. Then the virtual DOM will try to find the most efficient way to update the browsers DOM.\n\nUnlike browser DOM elements, React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements. The reason for this is that JavaScript is very fast and it is worth keeping a DOM tree in it to speedup its manipulation.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. List some of the major advantages and limitations of React?\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/react-features.png\" alt=\"React-Features\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n**Advantages:**  \n\n* It relies on a virtual-dom to know what is really changing in UI and will re-render only what has really changed, hence better performance wise\n* JSX makes components/blocks code readable. It displays how components are plugged or combined with.\n* React data binding establishes conditions for creation dynamic applications.\n* Prompt rendering. Using comprises methods to minimise number of DOM operations helps to optimise updating process and accelerate it.\nTestable. React native tools are offered for testing, debugging code.\n* SEO-friendly. React presents the first-load experience by server side rendering and connecting event-handlers on the side of the user:\n    * React.renderComponentToString is called on the server.\n    * React.renderComponent() is called on the client side.\n    * React preserves markup rendered on the server side, attaches event handlers.  \n\n**Limitations:**  \n\n* Learning curve. Being not full-featured framework it is required in-depth knowledge for integration user interface free library into MVC framework.\n* View-orientedness is one of the cons of ReactJS. It should be found 'Model' and 'Controller' to resolve 'View' problem.\n* Not using isomorphic approach to exploit application leads to search engines indexing problems.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why does React emphasize on unidirectional data flow?\n\nIt is also known as one-way data flow, which means the data has one, and only one way to be transferred to other parts of the application. In essence, this means child components are not able to update the data that is coming from the parent component. In React, data coming from a parent is called **props**.\n\nIn React this means that:\n\n* state is passed to the view and to child components\n* actions are triggered by the view\n* actions can update the state\n* the state change is passed to the view and to child components\n\nThe view is a result of the application state. State can only change when actions happen. When actions happen, the state is updated. One-way data binding provides us with some key advantages\n\n* Easier to debug, as we know what data is coming from where.\n* Less prone to errors, as we have more control over our data.\n* More efficient, as the library knows what the boundaries are of each part of the system.\n\nIn React, a state is always owned by one component. Any changes made by this state can only affect the components below it, i.e its `children`. Changing state on a component will never affect its parent or its siblings, only the children will be affected. This is the main reason that the state is often moved up in the component tree so that it can be shared between the components that need to access it.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to declare constant in react?\n\n```js\n// Constants.js\n\nexport const POSTURL = \"http://localhost:3000/api/v1/patterns\";\nexport const DELETEURL = \"http://localhost:3000/api/v1/patterns/\";\n\nexport const DeleteButton = require(\"./images/delete-icon.png\");\nexport const LoadingWheel = require(\"./images/loading-wheel.gif\");\n\n```\n\n```js\n// App.js\n\nimport * as Constants from \"./Constants\";\n\nconst employee = {\n  emp_id: 10,\n  name: \"Nakul Agate\",\n  email: \"nakul.agate@email.com\"\n};\n\nclass App extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cdiv\u003eEmployee Details :{JSON.stringify(employee)}\u003c/div\u003e\n        \u003cdiv\u003e\u003cimg src={Constants.LoadingWheel} alt=\"Loading...\" /\u003e\u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-constants-knzec?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Destructuring?\n\nDestructuring is a convenient way of accessing multiple properties stored in objects and arrays. It was introduced to JavaScript by ES6 and has provided developers with an increased amount of utility when accessing data properties in Objects or Arrays.\n\nWhen used, destructuring does not modify an object or array but rather copies the desired items from those data structures into variables. These new variables can be accessed later on in a React component.\n\n**Example:**\n\n```js\n/**\n * Destructuring in React\n */\nimport React from \"react\";\n\nexport default function App() {\n  // Destructuring\n  const [counter, setcounter] = React.useState(0);\n\n  return (\n    \u003c\u003e\n      \u003cbutton onClick={() =\u003e setcounter(counter + 1)}\u003e Increment \u003c/button\u003e\n      \u003cbutton onClick={() =\u003e setcounter(counter \u003e 0 ? counter - 1 : 0)}\u003e\n        Decrement\n      \u003c/button\u003e\n\n      \u003ch2\u003eResult: {counter}\u003c/h2\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/destructuring-in-react-6fxnbh?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why is it necessary to start component names with a capital letter?\n\nIn JSX, lower-case tag names are considered to be HTML tags. However, lower-case tag names with a dot (property accessor) aren\\'t.\n\nWhen an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string `\u003cdiv\u003e` or `\u003cspan\u003e` passed to `React.createElement`. Types that start with a capital letter like compile to `React.createElement(Foo)` and correspond to a component defined or imported in your JavaScript file.\n\n* `\u003ccomponent /\u003e` compiles to `React.createElement('component')` (html tag)\n* `\u003cComponent /\u003e` compiles to `React.createElement(Component)`\n* `\u003cobj.component /\u003e` compiles to `React.createElement(obj.component)`\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are fragments?\n\nFragments allows to group a list of children without adding extra nodes to the DOM.\n\n**Example:**\n\n```js\nclass App extends React.Component {\n  render() {\n    return (\n      \u003cReact.Fragment\u003e\n        \u003cChildA /\u003e\n        \u003cChildB /\u003e\n        \u003cChildC /\u003e\n      \u003c/React.Fragment\u003e\n    )\n  }\n}\n```\n\n**Benefits:**\n\n* It\\'s a tiny bit faster and has less memory usage (no need to create an extra DOM node). This only has a real benefit on very large and/or deep trees, but application performance often suffers from death by a thousand cuts. This is one cut less.\n* Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding divs in the middle makes it hard to keep the desired layout while extracting logical components.\n* The DOM inspector is less cluttered.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Virtual DOM?\n\nIn React, for every **DOM object**, there is a corresponding \"virtual DOM object\". A virtual DOM object is a representation of a DOM object, like a lightweight copy. A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing\\'s power to directly change what\\'s on the screen.\n\nManipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets drawn on the screen. So each time there is a change in the state of our application, virtual DOM gets updated first instead of the real DOM.\n\n**\u0026#9885; [Virtual DOM Example](https://codesandbox.io/s/react-virtual-dom-2w52y?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between ShadowDOM and VirtualDOM?\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/shadow-dom.png\" alt=\"DOM\" width=\"600px\" /\u003e\n\u003c/p\u003e\n\n**1. Document Object Model:**\n\nIt a way of representing a structured document via objects. It is cross-platform and language-independent convention for representing and interacting with data in HTML, XML, and others. Web browsers handle the DOM implementation details, so we can interact with it using JavaScript and CSS.\n\n**2. Virtual DOM:**\n\nVirtual DOM is any kind of representation of a real DOM. Virtual DOM is about avoiding unnecessary changes to the DOM, which are expensive performance-wise, because changes to the DOM usually cause re-rendering of the page. It allows to collect several changes to be applied at once, so not every single change causes a re-render, but instead re-rendering only happens once after a set of changes was applied to the DOM.\n\n**3. Shadow DOM:**\n\nShadow DOM is mostly about encapsulation of the implementation. A single custom element can implement more-or-less complex logic combined with more-or-less complex DOM. Shadow DOM refers to the ability of the browser to include a subtree of DOM elements into the rendering of a document, but not into the main document DOM tree.\n\n**Difference:**\n\nThe virtual DOM creates an additional DOM. The shadow DOM simply hides implementation details and provides isolated scope for web components.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 2. REACT SETUP\n\n\u003cbr/\u003e\n\n## Q. How to set up a react project with create react app?\n\nCreate React App is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration. This tool is wrapping all of the required dependencies like **Webpack**, **Babel** for React project itself.\n\n**Requirements:**\n\nThe Create React App is maintained by Facebook and can works on any platform, for example, macOS, Windows, Linux, etc. To create a React Project using create-react-app, you need to have installed the following things in your system.\n\n* [Node version \u003e= 14](https://nodejs.org/en/download/)\n* [Visual Studio Code Editor](https://code.visualstudio.com/download)\n\n**Installation:**\n\n```js\nnpx create-react-app my-app\ncd my-app\nnpm start\n```\n\n**Output:**\n\nRunning any of these commands will create a directory called **my-app** inside the current folder. Inside that directory, it will generate the initial project structure and install the transitive dependencies:\n\n```js\nmy-app\n├── README.md\n├── node_modules\n├── package.json\n├── .gitignore\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    ├── serviceWorker.js\n    └── setupTests.js\n```\n\n**Reference:**\n\n* *[https://create-react-app.dev/docs/getting-started/](https://create-react-app.dev/docs/getting-started/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the features of create react app?\n\n**Create React App** is a command-line program that lets us create a new React project easily and build the project into artifacts that we can deploy. It is created by the React team and creates a scaffold to the app.\n\nBelow are the list of some of the features provided by create react app.\n\n* React, JSX, ES6, Typescript and Flow syntax support.\n* Autoprefixed CSS\n* CSS Reset/Normalize\n* Live-editing CSS and JS in local development server.\n* A fast interactive unit test runner with built-in support for coverage reporting\n* A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps\n* An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What does eject do in create react app?\n\nThe `create-react-app` commands generate **React App** with an excellent configuration and helps you build your React app with the best practices in mind to optimize it. However, running the `eject` script will remove the single build dependency from your project. That means it will copy the configuration files and the transitive dependencies (e.g. `Webpack`, `Babel`, etc.) as dependencies in the `package.json` file. If you do that, you\\'ll have to ensure that the dependencies are installed before building your project.\n\nAfter running the `eject`, commands like `npm start` and `npm run build` will still work, but they will point to the copied scripts so you can tweak them. It won\\'t be possible to run it again since all scripts will be available except the eject one.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to put React in production mode?\n\nCreate a simple `hello-world-app` using [create-react-app](https://create-react-app.dev/docs/getting-started).\n\n```js\nnpx create-react-app hello-world-app\n```\n\nModify the `App.js` file as shown below.\n\n```js\nimport './App.css';\n\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cheader className=\"App-header\"\u003e\n        \u003ch1\u003eHello world app\u003c/h1\u003e\n      \u003c/header\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n\nRun the app local server by running the following command\n\n```js\nnpm start\n```\n\nOn the local server (http://localhost:3000) you can see a simple React app displaying a \"hello world\" message. The next step is to make this app production-ready for deployment. Inside the root directory run the following command:\n\n```js\nnpm run build\n```\n\nThis creates a build directory inside the root directory, which bundles your React app and minifies it into simple HTML, CSS, and JavaScript files. This build folder serves your app via a simple entry point, `index.html`, where your entire React app resides. Running your app via a remote server means running this `index.html` file on the server.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the common folder structures for React?\n\nReact doesn\\'t have opinions on how you put files into folders. That said there are a few common approaches popular in the ecosystem you may want to consider.\n\n**1. Grouping by features or routes:**\n\nOne common way to structure projects is to locate CSS, JS, and tests together inside folders grouped by feature or route.\n\n```js\ncommon/\n  Avatar.js\n  Avatar.css\n  APIUtils.js\n  APIUtils.test.js\nfeed/\n  index.js\n  Feed.js\n  Feed.css\n  FeedStory.js\n  FeedStory.test.js\n  FeedAPI.js\nprofile/\n  index.js\n  Profile.js\n  ProfileHeader.js\n  ProfileHeader.css\n  ProfileAPI.js\n```\n\n**2. Grouping by file type:**\n\nAnother popular way to structure projects is to group similar files together, for example:\n\n```js\napi/\n  APIUtils.js\n  APIUtils.test.js\n  ProfileAPI.js\n  UserAPI.js\ncomponents/\n  Avatar.js\n  Avatar.css\n  Feed.js\n  Feed.css\n  FeedStory.js\n  FeedStory.test.js\n  Profile.js\n  ProfileHeader.js\n  ProfileHeader.css\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the popular React-specific linter?\n\n**1. ESLint:**\n\nESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called `eslint-plugin-react`.\n\n```js\nnpm install -g eslint-plugin-react\n```\n\nThis will install the plugin we need, and in our ESLint config file, we just need a few extra lines.\n\n```js\n\"extends\": [\n    \"eslint:recommended\",\n    \"plugin:react/recommended\"\n]\n```\n\n```js\n\"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test --env=jsdom\",\n    \"eject\": \"react-scripts eject\",\n    \"lint\": \"eslint src/**/*.js src/**/*.jsx\"\n}\n```\n\n**2. eslint-plugin-jsx-a11y:**\n\nIt will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with `alt` text and `tabindex`, for example, will not be picked up by regular plugins.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the browser support for react applications?\n\nBy default, **Create React App** generated project supports all modern browsers. Support for Internet Explorer 9, 10, and 11 requires polyfills. For a set of polyfills to support older browsers, use **react-app-polyfill**.\n\nThe `browserslist` configuration controls the outputted JavaScript so that the emitted code will be compatible with the browsers specified.\n\n**Example:**\n\n```js\n// package.json\n\n\"browserslist\": {\n  \"production\": [\n    \"\u003e0.2%\",\n    \"not dead\",\n    \"not op_mini all\"\n  ],\n  \"development\": [\n    \"last 1 chrome version\",\n    \"last 1 firefox version\",\n    \"last 1 safari version\"\n  ]\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the use of Webpack and Babel in React?\n\n**1. Babel:**\n\nBabel is a JS transpiler that converts new JS code into old ones. It is a very flexible tool in terms of transpiling. One can easily add presets such as `es2015`, `es2016`, `es2017`, or `env`; so that Babel compiles them to ES5. Babel allows us to have a clean, maintainable code using the latest JS specifications without needing to worry about browser support.\n\n**2. Webpack:**\n\nWebpack is a modular build tool that has two sets of functionality — Loaders and Plugins. Loaders transform the source code of a module. For example, style-loader adds CSS to DOM using style tags. sass-loader compiles SASS files to CSS. babel-loader transpiles JS code given the presets. Plugins are the core of Webpack. They can do things that loaders can\\'t. For example, there is a plugin called UglifyJS that minifies and uglifies the output of webpack.\n\n**3. create-react-app:**\n\n[create-react-app](https://create-react-app.dev/docs/getting-started/), a popular tool that lets you set up a React app with just one command. You don\\'t need to get your hands dirty with Webpack or Babel because everything is preconfigured and hidden away from you.\n\n**Example:** Quick Start\n\n```bash\nnpx create-react-app my-app\ncd my-app\nnpm start\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between ReactDOM and React?\n\nThe ReactDOM module exposes DOM-specific methods, while React has the core tools intended to be shared by React on different platforms (e.g. React Native).\n\n**React** package contains: `React.createElement()`, `React.createClass()`, `React.Component()`, `React.PropTypes()`, `React.Children()`\n\n**ReactDOM** package contains: `ReactDOM.render()`, `ReactDOM.unmountComponentAtNode()`, `ReactDOM.findDOMNode()`, and react-dom/server that including: `ReactDOMServer.renderToString()` and `ReactDOMServer.renderToStaticMarkup()`.\n\n**Example:**\n\n```js\n/**\n * React vs ReactDOM\n */\nimport { createRoot } from \"react-dom/client\";\n\nexport default function App() {\n  return \u003ch1\u003eHello React\u003c/h1\u003e;\n}\n\nconst rootElement = document.getElementById(\"root\");\nconst root = createRoot(rootElement);\n\nroot.render(\u003cApp /\u003e);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-vs-reactdom-o52zfc?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is ReactDOM?\n\nReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page.\n\nReactDOM provides the developers with an API containing the following methods\n\n* render()\n* findDOMNode()\n* unmountComponentAtNode()\n* hydrate()\n* createPortal()\n\n**1. render():**\n\n```js\nReactDOM.render(element, container, callback)\n```\n\nRender a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components). If the React element was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element. If the optional callback is provided, it will be executed after the component is rendered or updated.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/reactdom-render-cyddr?file=/src/index.js)**\n\n**2. hydrate():**\n\n```js\nReactDOM.hydrate(element, container, callback)\n```\n\nThis method is equivalent to the `render()` method but is implemented while using server-side rendering. This function attempts to attach event listeners to the existing markup and returns a reference to the component or null if a stateless component was rendered.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hydrate-e2bw5?file=/src/index.js)**\n\n**3. unmountComponentAtNode():**\n\n```js\nReactDOM.unmountComponentAtNode(container)\n```\n\nThis function is used to unmount or remove the React Component that was rendered to a particular container. It returns true if a component was unmounted and false if there was no component to unmount.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-unmountcomponentatnode-yued6)**\n\n**4. findDOMNode():**\n\n```js\nReactDOM.findDOMNode(component)\n```\n\nIf this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-finddomnode-ft936?file=/src/index.js)**\n\n**5. createPortal():**\n\n```js\nReactDOM.createPortal(child, container)\n```\n\ncreatePortal allow us to render a component into a DOM node that resides outside the current DOM hierarchy of the parent component.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-portal-v2h6q?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to build a progressive web app with react?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between create-react-app and webpack?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between grunt and webpack?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 3. REACT JSX\n\n\u003cbr/\u003e\n\n## Q. What is JSX?\n\nJSX ( **JavaScript Expression** ) allows us to write HTML elements in JavaScript and place them in the DOM without any `createElement()` or `appendChild()` methods. JSX converts HTML tags into react elements. React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it.\n\n* It is faster because it performs optimization while compiling code to JavaScript.\n* It is also type-safe and most of the errors can be caught during compilation.\n* It makes it easier and faster to write templates.\n\nWhen JSX compiled, they actually become regular JavaScript objects. For instance, the code below:\n\n```js\nconst hello = \u003ch1 className = \"greet\"\u003e Hello World \u003c/h1\u003e\n```\n\nwill be compiled to\n\n```js\nconst hello = React.createElement {\n    type: \"h1\",\n    props: {\n      className: \"greet\",  \n      children: \"Hello World\"\n    }\n}\n```\n\n**Example:**\n\n```js\nexport default function App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003ch1\u003eHello World!\u003c/h1\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-jsx-zjmxvb?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How JSX prevents Injection Attacks?\n\nReact DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that\\'s not explicitly written in your application. Everything is converted to a string before being rendered.\n\nFor example, you can embed user input as below,\n\n```js\nexport default class JSXInjectionExample extends React.Component {\n\n  constructor(props) {\n    super(props);\n    this.state = {\n      userContent: `JSX prevents Injection Attacks Example \n          \u003cscript src=\"http://example.com/malicious-script.js\u003e\u003c/script\u003e`\n    };\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003eUser content: {this.state.userContent}\u003c/div\u003e\n    );\n  }\n}\n\n// Output\nUser content: JSX prevents Injection Attacks Example \n\u003cscript src=\"http://example.com/malicious-script.js\u003e\u003c/script\u003e\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-jsxinjection-ckmu8z?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the benefits of new JSX transform?\n\nThe React 17 release provides support for a new version of the JSX transform. There are three major benefits of new JSX transform,\n\n* It enables you to use JSX without having to import React.\n* The compiled output relatively improves the bundle size.\n* The future improvements provides the flexibility to reduce the number of concepts to learn React.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Is it possible to use React without rendering HTML?\n\nIt is possible with latest version (\u003e=16.2). Below are the possible options:\n\n```js\nrender() {\n  return false\n}\n```\n\n```js\nrender() {\n  return null\n}\n```\n\n```js\nrender() {\n  return []\n}\n```\n\n```js\nrender() {\n  return \u003cReact.Fragment\u003e\u003c/React.Fragment\u003e\n}\n```\n\n```js\nrender() {\n  return \u003c\u003e\u003c/\u003e\n}\n```\n\nNote that React can also run on the server side so, it will be possible to use it in such a way that it doesn\\'t involve any DOM modifications (but maybe only the virtual DOM computation).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to write comments in React and JSX?\n\nWriting comments in React components can be done just like comment in regular JavaScript classes and functions.\n\n**React comments:**\n\n```js\nfunction App() {\n\n  // Single line Comment\n\n  /*\n  * multi\n  * line\n  * comment\n  **/\n\n  return (\n    \u003ch1\u003eMy Application\u003c/h1\u003e\n  );\n}\n```\n\n**JSX comments:**\n\n```js\nexport default function App() {\n  return (\n    \u003cdiv\u003e\n      {/* A JSX comment */}\n      \u003ch1\u003eMy Application\u003c/h1\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to add custom DOM attributes in JSX?\n\nCustom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render function, like so:\n\n**Example:**\n\n```js\n// 1. Custom DOM Attribute\nrender() {\n  return (\n    \u003cdiv custom-attribute=\"some-value\" /\u003e\n  );\n}\n\n// 2. Data Attribute ( starts with \"data-\" )\nrender() {\n  return (\n    \u003cdiv data-id=\"10\" /\u003e\n  );\n}\n\n// 3. ARIA Attribute ( starts with \"aria-\" )\nrender() {\n  return (\n    \u003cbutton aria-label=\"Close\" onClick={onClose} /\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-custom-attribute-8enl34?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How many outermost elements can be there in a JSX expression?\n\nA JSX expression must have only one outer element. For Example:\n\n```js\nconst headings = (\n    \u003cdiv id = \"outermost-element\"\u003e\n       \u003ch1\u003eI am a heading \u003c/h1\u003e\n       \u003ch2\u003eI am also a heading\u003c/h2\u003e\n    \u003c/div\u003e\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to loop inside JSX?\n\nYou can simply use `Array.prototype.map` with ES6 arrow function syntax.\n\n**Example:**\n\n```js\n/**\n * Loop inside JSX\n */\nconst animals = [\n  { id: 1, animal: \"Dog\" },\n  { id: 2, animal: \"Bird\" },\n  { id: 3, animal: \"Cat\" },\n  { id: 4, animal: \"Mouse\" },\n  { id: 5, animal: \"Horse\" }\n];\n\nexport default function App() {\n  return (\n    \u003cul\u003e\n      {animals.map((item) =\u003e (\n        \u003cli key={item.id}\u003e{item.animal}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-jsx-loop-9x2pi?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you print false values in JSX?\n\nIn React, boolean values (`true` and `false`), `null`, and `undefined` are valid children, but these values will not be rendered in UI if you put them directly inside {} in JSX.\n\nFor example, all these JSX expressions will result in the same empty div:\n\n```js\n\u003cdiv /\u003e\n\u003cdiv\u003e\u003c/div\u003e\n\u003cdiv\u003e{false}\u003c/div\u003e\n\u003cdiv\u003e{null}\u003c/div\u003e\n\u003cdiv\u003e{undefined}\u003c/div\u003e\n\u003cdiv\u003e{true}\u003c/div\u003e\n```\n\nIf you want a value like `false`, `true`, `null`, or `undefined` to show in the output, you have to convert it to a string first.\n\n```js\n\u003cdiv\u003e{String(true)}\u003c/div\u003e\n\u003cdiv\u003e{String(false)}\u003c/div\u003e\n\u003cdiv\u003e{String(undefined)}\u003c/div\u003e\n\u003cdiv\u003e{String(null)}\u003c/div\u003e\n```\n\nIn the output, this will render `true`, `false`, `undefined`, and `null` respectively.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-rendering-false-values-1g1rm?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use React label element?\n\nIf you try to render a `\u003clabel\u003e` element bound to a text input using the standard `for` attribute, then it produces HTML missing that attribute and prints a warning to the console.\n\n```js\n\u003clabel for={'user'}\u003e{'User'}\u003c/label\u003e\n\u003cinput type={'text'} id={'user'} /\u003e\n```\n\nSince `for` is a reserved keyword in JavaScript, use `htmlFor` instead.\n\n```js\n\u003clabel htmlFor={'user'}\u003e{'User'}\u003c/label\u003e\n\u003cinput type={'text'} id={'user'} /\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use InnerHtml in React?\n\nThe **innerHTML** is risky because it is easy to expose users to a cross-site scripting (XSS) attack. React provides **dangerouslySetInnerHTML** as a replacement for innerHTML. It allows to set HTML directly from React by using `dangerouslySetInnerHTML` and passing an object with a `__html` key that holds HTML.\n\n**Example:**\n\n```js\n/**\n * InnerHtml in React\n */\nimport React from \"react\";\n\nexport default function App() {\n  return (\n    \u003cdiv\n      dangerouslySetInnerHTML={{\n        __html: \"\u003cp\u003eThis text is set using \u003cb\u003edangerouslySetInnerHTML\u003c/b\u003e\u003c/p\u003e\"\n      }}\n    \u003e\u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-dangerouslysetinnerhtml-i4wqq?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to show and hide elements in React\n\n**1. Returning Null:**\n\n```js\nconst AddToCart = ({ available }) =\u003e {\n  if (!available) return null\n\n  return (\n    \u003cdiv className=\"full tr\"\u003e\n      \u003cbutton className=\"product--cart-button\"\u003eAdd to Cart\u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n**2. Ternary Display:**\n\nWhen you need to control whether one element vs. another is displayed, or even one element vs. nothing at all (null), you can use the ternary operator embedded inside of a larger portion of JSX.\n\n```js\n\u003cdiv className=\"half\"\u003e\n  \u003cp\u003e{description}\u003c/p\u003e\n\n  {remaining === 0 ? (\n    \u003cspan className=\"product-sold-out\"\u003eSold Out\u003c/span\u003e\n  ) : (\n    \u003cspan className=\"product-remaining\"\u003e{remaining} remaining\u003c/span\u003e\n  )}\n\u003c/div\u003e\n```\n\nIn this case, if there are no products remaining, we will display \"Sold Out\"; otherwise we will display the number of products remaining.\n\n**3. Shortcut Display:**\n\nIt involves using a conditional inside of your JSX that looks like `checkIfTrue \u0026\u0026 \u003cspan\u003edisplay if true\u003c/span\u003e`. Because if statements that use `\u0026\u0026` operands stop as soon as they find the first value that evaluates to false, it won\\'t reach the right side (the JSX) if the left side of the equation evaluates to false.\n\n```js\n\u003ch2\u003e\n  \u003cspan className=\"product--title__large\"\u003e{nameFirst}\u003c/span\u003e\n  {nameRest.length \u003e 0 \u0026\u0026 (\n    \u003cspan className=\"product--title__small\"\u003e{nameRest.join(\" \")}\u003c/span\u003e\n  )}\n\u003c/h2\u003e\n```\n\n**4. Using Style Property:**\n\n```js\n\u003cdiv style={{ display: showInfo ? \"block\" : \"none\" }}\u003einfo\u003c/div\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4. REACT COMPONENTS\n\n\u003cbr/\u003e\n\n## Q. What are React components?\n\nComponents are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(`props`) and returns a React element that describes how a section of the UI (User Interface) should appear.\n\nIn React, a **Stateful Component** is a component that holds some state. A **Stateless component**, by contrast, has no state. Note that both types of components can use props.\n\n**1. Stateless Component:**\n\n```js\nimport React from 'react'\n\nconst ExampleComponent = (props) =\u003e {\n    return \u003ch1\u003eStateless Component - {props.message}\u003c/h1\u003e;\n};\n\nconst App = () =\u003e {\n  const message = 'React Interview Questions'\n  return (\n    \u003cdiv\u003e\n      \u003cExampleComponent message={message} /\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default App;\n```\n\nThe above example shows a stateless component named ExampleComponent which is inserted in the `\u003cApp/\u003e` component. The `ExampleComponent` just comprises of a `\u003ch1\u003e` element. Although the **Stateless component** has no state, it still receives data via props from a parent component.\n\n**2. Stateful Component:**\n\n```js\nimport React, { useState } from 'react'\n\nconst ExampleComponent = (props) =\u003e {\n  const [email, setEmail] = useState(props.defaultEmail)\n\n  const changeEmailHandler = (e) =\u003e {\n    setEmail(e.target.value)\n  }\n\n  return (\n    \u003cinput type=\"text\" value={email} onChange={changeEmailHandler} /\u003e\n  );\n}\n\n\nconst App = () =\u003e {\n  const defaultEmail = \"suniti.mukhopadhyay@gmail.com\"\n  return (\n    \u003cdiv\u003e\n      \u003cExampleComponent defaultEmail={defaultEmail} /\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default App;\n```\n\nThe above example shows a stateful component named **ExampleComponent** which is inserted in the `\u003cApp/\u003e` component. The **ExampleComponent** contains a `\u003cinput\u003e`. First of all, in the **ExampleComponent**, we need to assign **defaultEmail** by props to a local **state** by a `useState()` hook in **ExampleComponent**.\n\nNext, we have to pass **email** to **value** property of a input tag and pass a function **changeEmailHandler** to an `onChange()` event for a purpose keeping track of the current value of the input.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Component and Container in React?\n\nThe **presentational** components are concerned with the look, **container** components are concerned with making things work.\n\nFor example, this is a presentational component. It gets data from its props, and just focuses on showing an element\n\n```js\n/**\n * Presentational Component \n */\nconst Users = props =\u003e (\n  \u003cul\u003e\n    {props.users.map(user =\u003e (\n      \u003cli\u003e{user}\u003c/li\u003e\n    ))}\n  \u003c/ul\u003e\n)\n```\n\nOn the other hand this is a container component. It manages and stores its own data, and uses the presentational component to display it.\n\n```js\n/**\n * Container Component \n */\nclass UsersContainer extends React.Component {\n  constructor() {\n    this.state = {\n      users: []\n    }\n  }\n\n  componentDidMount() {\n    axios.get('/users').then(users =\u003e\n      this.setState({ users: users }))\n    )\n  }\n\n  render() {\n    return \u003cUsers users={this.state.users} /\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to import and export components using React.js?\n\n```js\n// Importing combination\nimport React, { Component } from 'react';\nimport ReactDOM from 'react-dom';\n\n// Wrapping components with braces if no default exports\nimport { Button }  from './Button';\n\n// Default exports ( recommended )\nimport  Button  from './Button';\n \nclass DangerButton extends Component {\n    render()\n    {\n        return \u003cButton color=\"red\" /\u003e;\n    }\n}\n\nexport default DangerButton; \n// or export DangerButton;\n```\n\nBy using default you express that\\'s going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called DangerButton by doing so: `import { DangerButton } from './comp/danger-button';` in this case, no default is needed\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between declarative and imperative in React.js?\n\n**1. Imperative programming:**\n\nIt is a programming paradigm that uses statements that change a program\\'s state.\n\n```js\nconst string = \"Hi there , I'm a web developer\";\nlet removeSpace = \"\";\nfor (let i = 0; i \u003c i.string.length; i++) {\n  if (string[i] === \" \") removeSpace += \"-\";\n  else removeSpace += string[i]; \n}\nconsole.log(removeSpace);\n```\n\nIn this example, we loop through every character in the string, replacing spaces as they occur. Just looking at the code, it doesn\\'t say much. Imperative requires lots of comments in order to understand code. Whereas in the declarative program, the syntax itself describes what should happen and the details of how things happen are abstracted way.\n\n**2. Declarative programming:**\n\nIt is a programming paradigm that expresses the logic of a computation without describing its control flow.\n\n**Example:**\n\n```js\nconst { render } = ReactDOM\nconst Welcome = () =\u003e (\n  \u003cdiv id=\"App\"\u003e\n    //your HTML code \n    //your react components\n  \u003c/div\u003e\n)\nrender(\n\u003cApp /\u003e,\ndocument.getElementById('root')\n)\n```\n\nReact is declarative. Here, the **Welcome** component describes the DOM that should be rendered. The render function uses the instructions declared in the component to build the DOM, abstracting away the details of how the DOM is to be rendered. We can clearly see that we want to render our **Welcome** component into the element with the ID of 'target'.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Element and Component?\n\n**1. React Element:**\n\nIt is a simple object that describes a DOM node and its attributes or properties. It is an immutable description object and you can not apply any methods on it.\n\n```js\nconst element = \u003ch1\u003eReact Element Example!\u003c/h1\u003e;\nReactDOM.render(element, document.getElementById('app'));\n```\n\n**2. React Component:**\n\nIt is a function or class that accepts an input and returns a React element. It has to keep references to its DOM nodes and to the instances of the child components.\n\n```js\nfunction Message() {\n  return \u003ch2\u003eReact Component Example!\u003c/h2\u003e;\n}\nReactDOM.render(\u003cMessage /\u003e, document.getElementById('app'));\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to conditionally render components in react?\n\nConditional rendering is a term to describe the ability to render different user interface (UI) markup if a condition is true or false. In React, it allows us to render different elements or components based on a condition.\n\n**1. Element Variables:**\n\nYou can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn\\'t change.\n\n```js\nfunction LogInComponent(props) {\n  const isLoggedIn = props.isLoggedIn;\n  if (isLoggedIn) {\n    return \u003cUserComponent /\u003e;\n  }\n  return \u003cGuestComponent /\u003e;\n}\n\nReactDOM.render(\n  \u003cLogInComponent isLoggedIn={false} /\u003e,\n  document.getElementById('root')\n);\n```\n\n**2. Inline If-Else with Conditional Operator:**\n\n```js\nrender() {\n  const isLoggedIn = this.state.isLoggedIn;\n  return (\n    \u003cdiv\u003e\n      {isLoggedIn\n        ? \u003cLogoutButton onClick={this.handleLogoutClick} /\u003e\n        : \u003cLoginButton onClick={this.handleLoginClick} /\u003e\n      }\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-conditional-render-xjvr10?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to conditionally add attributes to React components?\n\nInline conditionals in attribute props\n\n```js\n/**\n * Conditionally add attributes\n */\nimport React from \"react\";\n\nexport default function App() {\n  const [mood] = React.useState(\"happy\");\n\n  const greet = () =\u003e alert(\"Hi there! :)\");\n\n  return (\n    \u003cbutton onClick={greet} disabled={\"happy\" === mood ? false : true}\u003e\n      Say Hi\n    \u003c/button\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/conditional-attributes-n13jg0?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How would you prevent a component from rendering?\n\nReact **shouldComponentUpdate()** is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. This method only used when a component will stay static or pure.\n\nThe React `shouldComponentUpdate()` method return `true` if it needs to re-render or `false` to avoid being re-render.\n\n**Syntax:**\n\n```js\nshouldComponentUpdate(nextProps, nextState){ }\n```\n\n**Example:**\n\n```js\n/**\n * Prevent a component from rendering\n */\nexport default class App extends React.Component {\n  constructor() {\n    super();\n    this.state = {\n      countOfClicks: 0\n    };\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick() {\n    this.setState({\n      countOfClicks: this.state.countOfClicks + 1\n    });\n  }\n\n  shouldComponentUpdate(nextProps, nextState) {\n    console.log(\"this.state.countOfClicks\", this.state.countOfClicks);\n    console.log(\"nextState.countOfClicks\", nextState.countOfClicks);\n    return true;\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch2\u003eshouldComponentUpdate Example\u003c/h2\u003e\n        \u003cp\u003eCount of clicks: \u003cb\u003e{this.state.countOfClicks}\u003c/b\u003e\u003c/p\u003e\n        \u003cbutton onClick={this.handleClick}\u003eCLICK ME\u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-shouldcomponentupdate-mryjv?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When would you use StrictMode component in React?\n\nThe **StrictMode** is a tool for highlighting potential problems in an application. Like `Fragment`, `StrictMode` does not render any visible UI. It activates additional checks and warnings for its descendants.\n\nStrict mode checks are run in development mode only; they do not impact the production build.\n\n**Example:**\n\n```js\n/**\n * StrictMode\n */\nimport { StrictMode } from \"react\";\nimport MyComponent from \"./MyComponent\";\n\nexport default function App() {\n  return (\n    \u003cStrictMode\u003e\n      \u003cMyComponent /\u003e\n    \u003c/StrictMode\u003e\n  );\n}\n```\n\nReact StrictMode, in order to be efficient and avoid potential problems by any side-effects, needs to trigger some methods and lifecycle hooks twice. These are:\n\n* Class component constructor() method\n* The render() method\n* setState() updater functions (the first argument)\n* The static getDerivedStateFromProps() lifecycle\n* React.useState() function\n\n**Benefits of StrictMode:**\n\n* Identifying components with unsafe lifecycles\n* Warning about legacy string ref API usage\n* Warning about deprecated findDOMNode usage\n* Detecting unexpected side effects\n* Detecting legacy context API\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why to avoid using setState() after a component has been unmounted?\n\nCalling `setState()` after a component has unmounted will emit a warning. The \"setState warning\" exists to help you catch bugs, because calling `setState()` on an unmounted component is an indication that your app/component has somehow failed to clean up properly.\n\nSpecifically, calling `setState()` in an unmounted component means that your app is still holding a reference to the component after the component has been unmounted - which often indicates a memory leak.\n\n**Example:**\n\n```js\n/**\n * setState() in unmounted component\n */\nimport React, { Component } from \"react\";\nimport axios from \"axios\";\n\nexport default class App extends Component {\n  _isMounted = false; // flag to check Mounted\n\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      news: []\n    };\n  }\n\n  componentDidMount() {\n    this._isMounted = true;\n\n    axios\n      .get(\"https://hn.algolia.com/api/v1/search?query=react\")\n      .then((result) =\u003e {\n        if (this._isMounted) {\n          this.setState({\n            news: result.data.hits\n          });\n        }\n      });\n  }\n\n  componentWillUnmount() {\n    this._isMounted = false;\n  }\n\n  render() {\n    return (\n      \u003cul\u003e\n        {this.state.news.map((topic) =\u003e (\n          \u003cli key={topic.objectID}\u003e{topic.title}\u003c/li\u003e\n        ))}\n      \u003c/ul\u003e\n    );\n  }\n}\n```\n\nHere, even though the component got unmounted and the request resolves eventually, the flag in component will prevent to set the state of the React component after it got unmounted.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-setstate-in-unmount-qmjn7m?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Lifting State Up in ReactJS?\n\nThe common approach to share **state** between two components is to move the state to common parent of the two components. This approach is called as lifting state up in React.js. With the shared state, changes in state reflect in relevant components simultaneously.\n\n**Example:**\n\nThe App component containing PlayerContent and PlayerDetails component. PlayerContent shows the player name buttons. PlayerDetails shows the details of the in one line.\n\nThe app component contains the state for both the component. The selected player is shown once we click on the one of the player button.\n\n```js\n/**\n * Lifting State Up\n */\nimport React from \"react\";\nimport PlayerContent from \"./PlayerContent\";\nimport PlayerDetails from \"./PlayerDetails\";\n\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { selectedPlayer: [0, 0], playerName: \"\" };\n    this.updateSelectedPlayer = this.updateSelectedPlayer.bind(this);\n  }\n  updateSelectedPlayer(id, name) {\n    const arr = [0, 0, 0, 0];\n    arr[id] = 1;\n    this.setState({\n      playerName: name,\n      selectedPlayer: arr\n    });\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cPlayerContent\n          active={this.state.selectedPlayer[0]}\n          clickHandler={this.updateSelectedPlayer}\n          id={0}\n          name=\"Player 1\"\n        /\u003e\n        \u003cPlayerContent\n          active={this.state.selectedPlayer[1]}\n          clickHandler={this.updateSelectedPlayer}\n          id={1}\n          name=\"Player 2\"\n        /\u003e\n        \u003cPlayerDetails name={this.state.playerName} /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n```js\n/**\n * PlayerContent\n */\nimport React, { Component } from \"react\";\n\nexport default class PlayerContent extends Component {\n  render() {\n    return (\n      \u003cbutton\n        onClick={() =\u003e {\n          this.props.clickHandler(this.props.id, this.props.name);\n        }}\n        style={{ color: this.props.active ? \"red\" : \"blue\" }}\n      \u003e\n        {this.props.name}\n      \u003c/button\u003e\n    );\n  }\n}\n```\n\n```js\n/**\n * PlayerDetails\n */\nimport React, { Component } from \"react\";\n\nexport default class PlayerDetails extends Component {\n  render() {\n    return \u003ch2\u003e{this.props.name}\u003c/h2\u003e;\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-lifting-state-up-z8xkci?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is \"Children\" in React?\n\nIn React, **children** refer to the generic box whose contents are **unknown** until they\\'re passed from the parent component. Children allows to pass components as data to other components, just like any other prop you use.\n\nThe special thing about children is that React provides support through its `ReactElement API` and `JSX`. XML children translate perfectly to React children!\n\n**Example:**\n\n```js\n/**\n * Children in React\n */\nconst Picture = (props) =\u003e {\n  return (\n    \u003cdiv\u003e\n      \u003cimg src={props.src}/\u003e\n      {props.children}\n    \u003c/div\u003e\n  )\n}\n```\n\nThis component contains an `\u003cimg\u003e` that is receiving some props and then it is displaying `{props.children}`.\nWhenever this component is invoked `{props.children}` will also be displayed and this is just a reference to what is between the opening and closing tags of the component.\n\n```js\n/**\n * App.js\n */\n\nrender () {\n  return (\n    \u003cdiv className='container'\u003e\n      \u003cPicture key={picture.id} src={picture.src}\u003e\n          {/** what is placed here is passed as props.children **/}\n      \u003c/Picture\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Compound Components in React?\n\nThe Compound components are a pattern in which components are used together such that they share an implicit state that lets them communicate with each other in the background.\n\nInternally they are built to operate on a set of data that is passed in through children instead of props. Behind the scenes they make use of React\\'s lower level API such as `React.children.map()`, and `React.cloneElement()`. Using these methods, the component is able to express itself in such a way that promotes patterns of composition and extensibility.\n\n**Example:**\n\n```js\nfunction App() {\n  return (\n    \u003cMenu\u003e\n      \u003cMenuButton\u003e\n        Actions \u003cspan aria-hidden\u003e▾\u003c/span\u003e\n      \u003c/MenuButton\u003e\n      \u003cMenuList\u003e\n        \u003cMenuItem onSelect={() =\u003e alert('Download')}\u003eDownload\u003c/MenuItem\u003e\n        \u003cMenuItem onSelect={() =\u003e alert('Copy')}\u003eCreate a Copy\u003c/MenuItem\u003e\n        \u003cMenuItem onSelect={() =\u003e alert('Delete')}\u003eDelete\u003c/MenuItem\u003e\n      \u003c/MenuList\u003e\n    \u003c/Menu\u003e\n  )\n}\n```\n\nIn this example, the `\u003cMenu\u003e` establishes some shared implicit state. The `\u003cMenuButton\u003e`, `\u003cMenuList\u003e`, and `\u003cMenuItem\u003e` components each access and/or manipulate that state, and it\\'s all done implicitly. This allows you to have the expressive API you're looking for.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.1. FUNCTIONAL COMPONENTS\n\n\u003cbr/\u003e\n\n## Q. What are functional components in react?\n\nA React functional component is a simple JavaScript function that accepts **props** and returns a React element. It also referred as **stateless** components as it simply accept data and display them in some form.\n\nAfter the introduction of React Hooks, writing functional components has become the ​standard way of writing React components in modern applications.\n\n**Example:**\n\n```js\nfunction Welcome(props) {\n  return \u003ch1\u003eHello, {props.name}\u003c/h1\u003e;\n}\n\nconst element = \u003cWelcome name=\"World!\" /\u003e;\n\nReactDOM.render(\n  element,\n  document.getElementById('root')\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/MWmEmRj?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.2. CLASS COMPONENTS\n\n\u003cbr/\u003e\n\n## Q. What are class components in react?\n\nThe class component, a stateful/container component, is a regular ES6 class that extends the component class of the React library. It is called a stateful component because it controls how the state changes and the implementation of the component logic. Aside from that, they have access to all the different phases of a React lifecycle method.\n\n**Example:**\n\n```js\nclass Welcome extends React.Component {\n  render() {\n    return \u003ch1\u003eHello, {this.props.name}\u003c/h1\u003e;\n  }\n}\n\nconst element = \u003cWelcome name=\"World!\" /\u003e;\n\nReactDOM.render(\n  element,\n  document.getElementById('root')\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/BaRwZyB)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the recommended ordering of methods in class component?\n\n* static methods\n* constructor()\n* getChildContext()\n* componentWillMount()\n* componentDidMount()\n* componentWillReceiveProps()\n* shouldComponentUpdate()\n* componentWillUpdate()\n* componentDidUpdate()\n* componentWillUnmount()\n* click handlers or event handlers like `onClickSubmit()` or `onChangeDescription()`\n* getter methods for render like `getSelectReason()` or `getFooterContent()`\n* optional render methods like `renderNavigation()` or `renderProfilePicture()`\n* render()\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create a dynamic table in react?\n\n```js\n/**\n * Generate dynamic table in React\n */\nclass Table extends React.Component {\n   constructor(props) {\n      super(props)\n      this.state = {\n         employees: [\n            { id: 10, name: 'Swarna Sachdeva', email: 'swarna@email.com' },\n            { id: 20, name: 'Sarvesh Date', email: 'sarvesh@email.com' },\n            { id: 30, name: 'Diksha Meka', email: 'diksha@email.com' }\n         ]\n      }\n   }\n\n   renderTableHeader() {\n      let header = Object.keys(this.state.employees[0])\n      return header.map((key, index) =\u003e {\n         return \u003cth key={index}\u003e{key.toUpperCase()}\u003c/th\u003e\n      })\n   }\n\n   renderTableData() {\n      return this.state.employees.map((employee, index) =\u003e {\n         const { id, name, email } = employee \n         return (\n            \u003ctr key={id}\u003e\n               \u003ctd\u003e{id}\u003c/td\u003e\n               \u003ctd\u003e{name}\u003c/td\u003e\n               \u003ctd\u003e{email}\u003c/td\u003e\n            \u003c/tr\u003e\n         )\n      })\n   }\n\n   render() {\n      return (\n         \u003cdiv\u003e\n            \u003ch1 id='title'\u003eReact Dynamic Table\u003c/h1\u003e\n            \u003ctable id='employees'\u003e\n               \u003ctbody\u003e\n                  \u003ctr\u003e{this.renderTableHeader()}\u003c/tr\u003e\n                  {this.renderTableData()}\n               \u003c/tbody\u003e\n            \u003c/table\u003e\n         \u003c/div\u003e\n      )\n   }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/wvdeqBm?editors=0110)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to prevent component from rendering in React?\n\nYou can prevent component from rendering by returning `null` based on specific condition. This way it can conditionally render component.\n\nIn the example below, the `\u003cWarningBanner /\u003e` is rendered depending on the value of the prop called warn. If the value of the prop is `false`, then the component does not render:\n\n```js\nfunction WarningBanner(props) {\n  if (!props.warn) {\n    return null;\n  }\n\n  return (\n    \u003cdiv className=\"warning\"\u003e\n      Warning!\n    \u003c/div\u003e\n  );\n}\n```\n\n```js\nclass Page extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {showWarning: true};\n    this.handleToggleClick = this.handleToggleClick.bind(this);\n  }\n\n  handleToggleClick() {\n    this.setState(state =\u003e ({\n      showWarning: !state.showWarning\n    }));\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        { /* Prevent component render if value of the prop is false */}\n        \u003cWarningBanner warn={this.state.showWarning} /\u003e\n        \u003cbutton onClick={this.handleToggleClick}\u003e\n          {this.state.showWarning ? 'Hide' : 'Show'}\n        \u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nReactDOM.render(\n  \u003cPage /\u003e,\n  document.getElementById('root')\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/GRmMvWr?editors=0110)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you set a timer to update every second?\n\nUsing `setInterval()` inside React components allows us to execute a function or some code at specific intervals. A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, we can use the `clearInterval()` method.\n\n**Example:**\n\n```js\nclass Clock extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {\n      time: new Date().toLocaleString()\n    }\n  }\n  componentDidMount() {\n    this.intervalID = setInterval(\n      () =\u003e this.tick(),\n      1000\n    )\n  }\n  componentWillUnmount() {\n    clearInterval(this.intervalID)\n  }\n  tick() {\n    this.setState({\n      time: new Date().toLocaleString()\n    })\n  }\n  render() {\n    return (\n      \u003cp className=\"App-clock\"\u003e\n        The time is {this.state.time}.\n      \u003c/p\u003e\n    )\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Differentiate between stateful and stateless components?\n\nStateful and stateless components have many different names. They are also known as:\n\n– Container vs Presentational components  \n– Smart vs Dumb components  \n\nThe literal difference is that one has state, and the other does not. That means the stateful components are keeping track of changing data, while stateless components print out what is given to them via props, or they always render the same thing.\n\n**Example:** Stateful/Container/Smart component\n\n```js\nclass Welcome extends React.Component {\n  render() {\n    return \u003ch1\u003eThis is a React Class Component\u003c/h1\u003e;\n  }\n}\n```\n\n**Example:** Stateless/Presentational/Dumb component\n\n```js\nfunction welcome(props) {\n  return \u003ch1\u003eThis is a React Functional Component\u003c/h1\u003e;\n}\n```\n\n|Class Components                               |Functional Components                                 |\n|-----------------------------------------------|-------------------------------------------------------|\n|Class components need to extend the component from \"React.Component\" and create a render function that returns the required element. | Functional components are like normal functions which take \"props\" as the argument and return the required element.|\n|They are also known as stateful components.    |They are also known as stateless components.|\n|They implement logic and the state of the component.|They accept some kind of data and display it in the UI.|\n|Lifecycle methods can be used inside them.     |Lifecycle methods cannot be used inside them.|\n|It needs to store state therefore constructors are used.|Constructors are not used in it.|\n|It has to have a \"render()\" method inside that. |It does not require a render method.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of using super constructor with props argument?\n\nThe `super()` keyword is used to call the parent constructor. `super(props)` would pass `props` to the parent constructor.\n\n```js\n/**\n * super constructor\n */\nclass App extends React.Component {\n  constructor(props) {\n      super(props)\n      this.state = {}\n   }\n\n  // React says we have to define render()\n  render() {\n    return \u003cdiv\u003eHello world\u003c/div\u003e\n  }\n}\n\nexport default App\n```\n\nHere, `super(props)` would call the `React.Component` constructor passing in props as the argument.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Element, Component and Component instance in React?\n\n**1. React Elements:**\n\nA React Element is just a plain old JavaScript Object without own methods. It has essentially four properties:\n\n* **type**: a String representing an HTML tag or a reference referring to a React Component\n* **key**: a String to uniquely identify an React Element\n* **ref**: a reference to access either the underlying DOM node or React Component Instance)\n* **props**: (properties Object)\n\nA React Element is not an instance of a React Component. It is just a simplified \"description\" of how the React Component Instance to be created should look like.\n\n**2. React Components and React Component Instances:**\n\nA React Component is used by extending `React.Component`. If a React Component is instantiated it expects a props Object and returns an instance, which is referred to as a React Component Instance.\n\nA React Component can contain state and has access to the React Lifecycle methods. It must have at least a `render` method, which returns a React Element(-tree) when invoked.\n\n**Example:**\n\n```js\n/**\n * React Component Instances\n */\nimport React from 'react'\nimport ReactDOM from 'react-dom'\n\nclass MyComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    console.log('This is a component instance:' + this)\n  }\n\n  render() {\n    const another_element = \u003cdiv\u003eHello, World!\u003c/div\u003e\n    console.log('This is also an element:' + another_element)\n    return another_element\n  }\n}\n\nconsole.log('This is a component:' + MyComponent)\n\nconst element = \u003cMyComponent/\u003e\nconsole.log('This is an element:' + element)\n\nReactDOM.render(element, document.getElementById('root'));\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What does shouldComponentUpdate do and why is it important?\n\nThe `shouldComponentUpdate()` method allows Component to exit the Update life cycle if there is no reason to apply a new render. React does not deeply compare `props` by default. When `props` or `state` is updated React assumes we need to re-render the content.\n\nThe default implementation of this function returns true so to stop the re-render you need to return false here:\n\n```js\nshouldComponentUpdate(nextProps, nextState) {\n  console.log(nextProps, nextState)\n  console.log(this.props, this.state)\n  return false  \n}\n```\n\n**Preventing unnecessary renders:**\n\nThe `shouldComponentUpdate()` method is the first real life cycle optimization method that we can leverage in React. It checks the current props and state, compares it to the next props and state and then returns true if they are different, or false if they are the same. This method is not called for the initial render or when `forceUpdate()` is used.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of render() function in React?\n\nThe React class components uses render() function. It is used to update the UI.\n\n**Purpose of render():**\n\n* React renders HTML to the web page by using a function called render().\n* The purpose of the function is to display the specified HTML code inside the specified HTML element.\n* In the render() method, we can read props and state and return our JSX code to the root component of our app.\n* In the render() method, we cannot change the state, and we cannot cause side effects ( such as making an HTTP request to the webserver).\n\n```js\n/**\n * render() function\n * \n * React v18.0.0\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\n\nclass App extends React.Component {\n  render() {\n    return \u003ch1\u003eRender() Method Example\u003c/h1\u003e;\n  }\n}\n\nconst container = document.getElementById(\"root\");\nconst root = createRoot(container);\nroot.render(\u003cApp /\u003e);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-render-l2q7qk?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.2.1. REACT LIFECYCLE\n\n\u003cbr/\u003e\n\n## Q. What are the different phases of React component lifecycle?\n\nReact provides several methods that notify us when certain stage of this process occurs. These methods are called the component lifecycle methods and they are invoked in a predictable order. The lifecycle of the component is divided into four phases.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/react-lifecycle.png\" alt=\"React component lifecycle\" width=\"800px\" /\u003e\n\u003c/p\u003e\n\n**1. Mounting:**  \n\nThese methods are called in the following order when an instance of a component is being created and inserted into the DOM:\n\n* `constructor()`\n* `getDerivedStateFromProps()`\n* `render()`\n* `componentDidMount()`\n\n**2. Updating:**  \n\nThe next phase in the lifecycle is when a component is updated. A component is updated whenever there is a change in the component\\'s state or props.\n\nReact has five built-in methods that gets called, in this order, when a component is updated:\n\n* `getDerivedStateFromProps()`\n* `shouldComponentUpdate()`\n* `render()`\n* `getSnapshotBeforeUpdate()`\n* `componentDidUpdate()`\n\n**3. Unmounting:**  \n\nThe next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.\n\n* `componentWillUnmount()`\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make component to perform an action only once when the component initially rendered?\n\n**1. Using Class Component:**\n\nThe `componentDidMount()` lifecycle hook can be used with class components. Any actions defined within a `componentDidMount()` lifecycle hook are called only once when the component is first mounted.\n\n**Example:**\n\n```js\nclass Homepage extends React.Component {\n  componentDidMount() {\n    trackPageView('Homepage')\n  }\n  render() {\n    return \u003cdiv\u003eHomepage\u003c/div\u003e\n  }\n}\n```\n\n**2. Using Function Component:**\n\nThe `useEffect()` hook can be used with function components. The `useEffect()` hook is more flexible than the lifecycle methods used for class components. It receives two parameters:\n\n* The first parameter it takes is a callback function to be executed.\n* The optional second parameter it takes is an array containing any variables that are to be tracked.\n\nThe value passed as the second argument controls when the callback is executed:\n\n* If the second parameter is **undefined**, the callback is executed every time that the component is rendered.\n* If the second parameter contains an array of variables, then the callback will be executed as part of the first render cycle and will be executed again each time an item in the array is modified.\n* If the second parameter contains an empty array, the callback will be executed only once as part of the first render cycle.\n\n**Example:**\n\n```js\nconst Homepage = () =\u003e {\n  useEffect(() =\u003e {\n    trackPageView('Homepage')\n  }, [])\n  \n  return \u003cdiv\u003eHomepage\u003c/div\u003e\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the typical pattern for rendering a list of components from an array of data?  \n\nThe usual pattern for rendering lists of components often ends with delegating all of the responsibilities of each child component to the entire list container component. But with a few optimizations, we can make a change in a child component not cause the parent component to re-render.\n\n**Example:** using custom `shouldComponentUpdate()`\n\n```js\n/**\n * shouldComponentUpdate()\n */\nclass AnimalTable extends React.Component\u003cProps, never\u003e {\n  shouldComponentUpdate(nextProps: Props) {\n    return !nextProps.animalIds.equals(this.props.animalIds);\n  }\n  ...\n```\n\nHere, `shouldComponentUpdate()` will return false if the props its receiving are equal to the props it already has. And because the AnimalTable is receiving just a List of string IDs, a change in the adoption status won\\'t cause AnimalTable to receive a different set of IDs.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between useEffect() vs componentDidMount()?\n\nIn react when we use class based components we get access to lifecycle methods ( like `componentDidMount()`, `componentDidUpdate(), etc ). But when we want use a functional component and also we want to use lifecycle methods, then using useEffect() we can implement those lifecycle methods.\n\n**1. componentDidMount():**\n\nThe `componentDidMount()` and `useEffect()` run after the mount. However useEffect() runs after the paint has been committed to the screen as opposed to before. This means we would get a flicker if needed to read from the DOM, then synchronously set state to make new UI.\n\nThe `useLayoutEffect()` was designed to have the same timing as componentDidMount(). So `useLayoutEffect(fn, [])` is a much closer match to componentDidMount() than useEffect(fn, []) -- at least from a timing standpoint.\n\n```js\n/**\n * componentDidMount() in Class Component\n */\nimport React, { Component } from \"react\";\n\nexport default class SampleComponent extends Component {\n  componentDidMount() {\n    // code to run on component mount\n  }\n  render() {\n    return \u003c\u003ecomponentDidMount Example\u003c/\u003e;\n  }\n}\n```\n\n**2. useEffect():**\n\n```js\n/**\n * useEffect() in Functional Component\n */\nimport React, { useEffect } from \"react\";\n\nconst SampleComponent = () =\u003e {\n  useEffect(() =\u003e {\n    // code to run on component mount\n  }, []);\n  return \u003c\u003euseEffect Example\u003c/\u003e;\n};\nexport default SampleComponent;\n```\n\nWhen `useEffect()` is used to get data from server.\n\n* The first argument is a callback that will be fired after browser layout and paint. Therefore it does not block the painting process of the browser.\n* The second argument is an array of values (usually props).\n* If any of the value in the array changes, the callback will be fired after every render.\n* When it is not present, the callback will always be fired after every render.\n* When it is an empty list, the callback will only be fired once, similar to componentDidMount.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why is a component constructor called only once?\n\nReact\\'s **reconciliation algorithm** assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it\\'s the same component as before, so reuses the previous instance rather than creating a new one.\n\nIf you give each component a unique key `prop`, React can use the key change to infer that the component has actually been substituted and will create a new one from scratch, giving it the full component lifecycle.\n\n```js\nrenderContent() {\n  if (this.state.activeItem === 'item-one') {\n    return (\n      \u003cContent title=\"First\" key=\"first\" /\u003e\n    )\n  } else {\n    return (\n      \u003cContent title=\"Second\" key=\"second\" /\u003e\n    )\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between componentDidMount() and componentWillMount()?\n\n**componentDidMount():**\n\nThe `componentDidMount()` is executed after the first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution such as `setTimeout()` or `setInterval()`.\n\n**Example:**\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {\n      data: 'Alex Belfort'\n    }\n  }\n\n  getData(){\n    setTimeout(() =\u003e {\n      console.log('Our data is fetched')\n      this.setState({\n        data: 'Hello Alex'\n      })\n    }, 1000)\n  }\n\n  componentDidMount() {\n    this.getData()\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        {this.state.data}\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default App\n```\n\n**componentWillMount():**\n\nThe `componentWillMount()` method is executed before rendering, on both the server and the client side. `componentWillMount()` method is the least used lifecycle method and called before any HTML element is rendered. It is useful when we want to do something programatically right before the component mounts.\n\n**Example:**\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {\n      data: 'Alex Belfort'\n    }\n  }\n  componentWillMount() {\n    console.log('First this called')\n  }\n\n  getData() {\n    setTimeout(() =\u003e {\n      console.log('Our data is fetched')\n      this.setState({\n        data: 'Hello Alex'\n      })\n    }, 1000)\n  }\n\n  componentDidMount() {\n    this.getData()\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        {this.state.data}\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default App\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Is it good to use setState() in componentWillMount() method?\n\nAvoid async initialization in `componentWillMount()`.\n\n`componentWillMount()` is invoked immediately before mounting occurs. It is called before `render()`, therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.\n\nMake async calls for component initialization in `componentDidMount()` instead of `componentWillMount()`\n\n```js\nfunction componentDidMount() {\n  axios.get(`api/messages`)\n    .then((result) =\u003e {\n      const messages = result.data\n      console.log(\"COMPONENT WILL Mount messages : \", messages);\n      this.setState({\n        messages: [...messages.content]\n      })\n    })\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use componentWillUnmount() with Functional Components in React?\n\nThe **useEffect()** can be used to manage API calls, as well as implementing **componentWillMount()**, and **componentWillUnmount()**.\n\nIf we pass an empty array as the second argument, it tells useEffect to fire on component load. This is the only time it will fire.\n\n```js\nimport React, { useEffect } from 'react';\n\nconst ComponentExample =\u003e () =\u003e {\n   useEffect( () =\u003e {\n      // Anything in here is fired on component mount.\n   }, []);\n}\n```\n\nIf you add a return function inside the useEffect() function, it is triggered when a component unmounts from the DOM.\n\n```js\nimport React, { useEffect } from 'react';\n\nconst ComponentExample =\u003e () =\u003e {\n    useEffect(() =\u003e {\n        return () =\u003e {\n            // Anything in here is fired on component unmount.\n        }\n    }, [])\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.3. PURE COMPONENTS\n\n\u003cbr/\u003e\n\n## Q. What are Pure Components in React?\n\n**Pure Components** in React are the components which do not re-renders when the value of state and props has been updated with the same values. Pure Components restricts the re-rendering ensuring the higher performance of the Component.\n\n**Features of React Pure Components:**\n\n* Prevents re-rendering of Component if props or state is the same\n* Takes care of `shouldComponentUpdate()` implicitly\n* `State()` and `Props` are Shallow Compared\n* Pure Components are more performant in certain cases\n\n**Example:**\n\n```js\n/**\n * React Pure Component\n */\nimport React from \"react\";\n\nexport default class App extends React.PureComponent {\n  constructor() {\n    super();\n    this.state = {\n      userArray: [1, 2, 3, 4, 5]\n    };\n    // Here we are creating the new Array Object during setState using \"Spread\" Operator\n    setInterval(() =\u003e {\n      this.setState({\n        userArray: [...this.state.userArray, 6]\n      });\n    }, 1000);\n  }\n\n  render() {\n    return \u003cb\u003eArray Length is: {this.state.userArray.length}\u003c/b\u003e;\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-purecomponent-gpegf8?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between Pure Component vs Component?\n\nPureComponent is exactly the same as Component except that it handles the `shouldComponentUpdate()` method. The major difference between React.PureComponent and React.Component is PureComponent does a shallow comparison on state change. It means that when comparing scalar values it compares their values, but when comparing objects it compares only references. It helps to improve the performance of the app.\n\nA component rerenders every time its parent rerenders, regardless of whether the component\\'s props and state have changed.\nOn the other hand, a pure component will not rerender if its parent rerenders, unless the pure component\\'s `props` (or `state`) have changed.\n\n**When to use React.PureComponent:**\n\n* State/Props should be an immutable object\n* State/Props should not have a hierarchy\n* We should call forceUpdate when data changes\n\n**Example:**\n\n```js\n// Regular class component\nclass App extends React.Component {\n  render() {\n    return \u003ch1\u003eComponent Example !\u003c/h1\u003e\n  }\n}\n\n// React Pure class component\nclass Message extends React.Component {\n  render() {\n    return \u003ch1\u003ePureComponent Example !\u003c/h1\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the problems of using render props with PureComponent?\n\nIf you create a function inside a **render** method, it negates the purpose of pure component. Because the shallow prop comparison will always return **false** for new props, and each **render** in this case will generate a new value for the render prop. You can solve this issue by defining the render function as instance method.\n\n**Example:**\n\n```js\nclass Mouse extends React.PureComponent {\n  // Mouse Component...\n}\n\nclass MouseTracker extends React.Component {\n  // Defined as an instance method, `this.renderTheCat` always\n  // refers to *same* function when we use it in render\n  renderTheCat(mouse) {\n    return \u003cCat mouse={mouse} /\u003e;\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eMove the mouse around!\u003c/h1\u003e\n        {/* define the render function as instance method */}\n        \u003cMouse render={this.renderTheCat} /\u003e \n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When to use PureComponent over Component?\n\n* We want to avoid re-rendering cycles of component when its props and state are not changed\n* The state and props of component are immutable\n* We do not plan to implement own `shouldComponentUpdate()` lifecycle method.\n\nOn the other hand, we should not use `PureComponent()` as a base component if:\n\n* props or state are not immutable\n* Plan to implement own `shouldComponentUpdate()` lifecycle method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.4. HIGHER ORDER COMPONENTS\n\n\u003cbr/\u003e\n\n## Q. What are Higher Order Components in React.js?\n\nA **Higher-Order Component(HOC)** is a function that takes a component and returns a new component. It is the advanced technique in React.js for reusing a component logic.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/Higher-Order-Components.jpg\" alt=\"Higher Order Components\" width=\"300px\" /\u003e\n\u003c/p\u003e\n\nHigher-Order Components are not part of the React API. They are the pattern that emerges from React\\'s compositional nature. The component transforms props into UI, and a higher-order component converts a component into another component. The examples of HOCs are Redux\\'s connect and Relay\\'s createContainer.\n\n```js\n/**\n * Higher Order Component\n */\nimport React, { Component } from \"react\";\n\nexport default function Hoc(HocComponent) {\n  return class extends Component {\n    render() {\n      return (\n        \u003cdiv\u003e\n          \u003cHocComponent\u003e\u003c/HocComponent\u003e\n        \u003c/div\u003e\n      );\n    }\n  };\n}\n```\n\n```js\n/**\n * App.js\n */\nimport React, { Component } from \"react\";\nimport Hoc from \"./HOC\";\n\nexport default class App extends Component {\n  render() {\n    return \u003ch2\u003eHigher Order Component!\u003c/h2\u003e;\n  }\n}\nApp = Hoc(App);\n```\n\n**Note:**\n\n* A HOC does not modify or mutate components. It creates a new one.\n* A HOC is used to compose components for code reuse.\n* A HOC is a pure function. It has no side effects, returning only a new component.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hoc-3qrt5b?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the benefits of using HOC?\n\n**Benefits:**\n\n* Importantly they provided a way to reuse code when using ES6 classes.\n* No longer have method name clashing if two HOC implement the same one.\n* It is easy to make small reusable units of code, thereby supporting the single responsibility principle.\n* Apply multiple HOCs to one component by composing them. The readability can be improve using a compose function like in Recompose.\n\n**Problems:**\n\n* Boilerplate code like setting the **displayName** with the HOC function name e.g. (**`withHOC(Component)`**) to help with debugging.\n* Ensure all relevant props are passed through to the component.\n* Hoist static methods from the wrapped component.\n* It is easy to compose several HOCs together and then this creates a deeply nested tree making it difficult to debug.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are Higher Order Component factory implementations?\n\nCreating a higher order component basically involves manipulating WrappedComponent which can be done in two ways:\n\n* Props Proxy\n* Inheritance Inversion\n\nBoth enable different ways of manipulating the WrappedComponent.\n\n**1. Props Proxy:**\n\nIn this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent. We also pass through the props that the HOC receives, hence the name **Props Proxy**.\n\n**Example:**\n\n```js\nfunction ppHOC(WrappedComponent) {\n   return class PP extends React.Component {\n     render() {\n       return \u003cWrappedComponent {...this.props}/\u003e\n     }\n   }\n}\n```\n\nProps Proxy can be implemented via a number of ways\n\n* Manipulating props\n* Accessing the instance via Refs\n* Abstracting State\n* Wrapping the WrappedComponent with other elements\n\n**2. Inheritance Inversion:**\n\nInheritance Inversion allows the HOC to have access to the WrappedComponent instance via `this` keyword, which means it has access to the `state`, `props`, component lifecycle hooks and the `render` method.\n\n**Example:**\n\n```js\nfunction iiHOC(WrappedComponent) {\n   return class Enhancer extends WrappedComponent {\n     render() {\n       return super.render()\n     }\n   }\n}\n```\n\nInheritance Inversion can be used in:\n\n* Conditional Rendering (Render Highjacking)\n* State Manipulation\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Inheritance Inversion (iiHOC) in react?\n\nInheritance Inversion gives the HOC access to the WrappedComponent instance via this, which means we can use the `state`, `props`, component lifecycle and even the `render` method.\n\n**Example:**\n\n```js\n/**\n * Inheritance Inversion\n */\nclass Welcome extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e Welcome {his.props.user}\u003c/div\u003e\n    )\n  }\n}\n\nconst withUser = (WrappedComponent) =\u003e {\n  return class extends React.Component {\n    render() {\n      if(this.props.user) {\n        return  (\n          \u003cWrappedComponent {...this.props} /\u003e\n        )\n      }\n      return \u003cdiv\u003eWelcome Guest!\u003c/div\u003e\n    }\n  }\n}\n\nconst withLoader = (WrappedComponent) =\u003e {\n  return class extends WrappedComponent {\n    render() {\n      const { isLoader } = this.props\n      if(!isLoaded) {\n        return \u003cdiv\u003eLoading...\u003c/div\u003e\n      }\n      return super.render()\n    }\n  }\n}\n\nexport default withLoader(withUser(Welcome))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create props proxy for Higher Order Component component?\n\nIt\\'s nothing more than a function, propsProxyHOC, that receives a Component as an argument (in this case we\\'ve called the argument WrappedComponent) and returns a new component with the WrappedComponent within.\n\nWhen we return the Wrapped Component we have the possibility to manipulate props and to abstract state, even passing state as a prop into the Wrapped Component.\n\nWe can create `props` passed to the component using props proxy pattern as below\n\n```js\nconst propsProxyHOC = (WrappedComponent) =\u003e {\n\n  return class extends React.Component {\n    render() {\n      const newProps = {\n        user: currentLoggedInUser\n      }\n\n      return \u003cWrappedComponent {...this.props} {...newProps} /\u003e\n    }\n  }\n}\n```\n\n**Props Proxy HOCs are useful to the following situations:**\n\n* Manipulating props\n* Accessing the instance via Refs (be careful, avoid using refs)\n* Abstracting State\n* Wrapping/Composing the WrappedComponent with other elements\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use decorators in React?\n\nDecorators provide a way of calling Higher-Order functions. It simply take a function, modify it and return a new function with added functionality. The key here is that they don\\'t modify the original function, they simply add some extra functionality which means they can be reused at multiple places.\n\n**Example:**\n\n```js\nexport const withUniqueId = (Target) =\u003e {\n  return class WithUniqueId extends React.Component {\n    uid = uuid();\n\n    render() {\n      return \u003cTarget {...this.props} uuid={this.uid} /\u003e;\n    }\n  };\n}\n```\n\n```js\n@withUniqueId\nclass UniqueIdComponent extends React.Component {\n  render() {\n    return \u003cdiv\u003eGenerated Unique ID is: {this.props.uuid}\u003c/div\u003e;\n  }\n}\n\nconst App = () =\u003e (\n  \u003cdiv\u003e\n    \u003ch2\u003eDecorators in React!\u003c/h2\u003e\n    \u003cUniqueIdComponent /\u003e\n  \u003c/div\u003e\n);\n```\n\n*Note: Decorators are an experimental feature in React that may change in future releases.*\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-decorators-386v5?file=/src/index.js:113-361)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of displayName class property?\n\nThe **displayName** string is used in debugging messages. Usually, you don\\'t need to set it explicitly because it\\'s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.\n\n**Example:**\n\n```js\nfunction withSubscription(WrappedComponent) {\n  \n  class WithSubscription extends React.Component {/* ... */}\n  \n  WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;\n  return WithSubscription;\n}\n\nfunction getDisplayName(WrappedComponent) {\n  return WrappedComponent.displayName || WrappedComponent.name || 'Component';\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4.5. LAZY LOADING\n\n\u003cbr/\u003e\n\n## Q. How to set up lazy loading components in React?\n\n**1. REACT.LAZY():**\n\n**React.lazy** is a function that lets you load components lazily through what is called code splitting without help from any external libraries. It makes possible for us to dynamically import components but they are rendered like regular components. This means that the bundle containing the component will only be loaded when the component is rendered.\n\nReact.lazy() takes a function that returns a promise as it\\'s argument, the function returns a promise by calling import() to load the content. The returned Promise resolves to a module with a default containing the React Component.\n\n```js\n// Without Lazy\nimport MyComponent from './MyComponent';\n \n// With Lazy\nconst MyComponent = React.lazy(() =\u003e import('./MyComponent'));\n```\n\n**2. SUSPENSE:**\n\n**React.Suspense** is a component that can be used to wrap lazy components. A React.Suspense takes a fallback prop that can be any react element, it renders this prop as a placeholder to deliver a smooth experience and also give user feedback while the lazy component is being loaded.\n\n```js\n/**\n * Suspense\n */\nimport React, { Suspense } from 'react';\n\nconst MyComponent = React.lazy(() =\u003e import('./MyComponent'));\n\nconst App = () =\u003e {\n  return (\n    \u003cdiv\u003e\n      \u003cSuspense fallback={\u003cdiv\u003eLoading ... \u003c/div\u003e}\u003e\n        \u003cMyComponent /\u003e\n      \u003c/Suspense\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**Example:**\n\n```js\n/**\n * React Lazy Loading Routes\n */\nimport React, { Suspense, lazy } from \"react\";\nimport { Switch, BrowserRouter as Router, Route, Link } from \"react-router-dom\";\n\nconst Home = lazy(() =\u003e import(\"./Home\"));\nconst ContactUs = lazy(() =\u003e import(\"./ContactUs\"));\nconst HelpPage = lazy(() =\u003e import(\"./Help\"));\n\nexport default function App() {\n  return (\n      \u003cRouter\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cLink to=\"/\"\u003eHome\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/contact-us\"\u003eContactUs\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/help\"\u003eHelpPage\u003c/Link\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n        \u003chr /\u003e\n        \u003cSuspense fallback={\u003ch1\u003eLoading...\u003c/h1\u003e}\u003e\n          \u003cSwitch\u003e\n            \u003cRoute exact component={Home} path=\"/\" /\u003e\n            \u003cRoute component={ContactUs} path=\"/contact-us\" /\u003e\n            \u003cRoute component={HelpPage} path=\"/help\" /\u003e\n          \u003c/Switch\u003e\n        \u003c/Suspense\u003e\n      \u003c/Router\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-lazy-loading-967o2?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 5. REACT PROPS\n\n\u003cbr/\u003e\n\n## Q. What is props in React?\n\n**Props** is a special keyword in React, which stands for properties and is being used for passing data from one component to another. However, callback functions can also be passed, which can be executed inside the child to initiate an update.\n\nProps are **immutable** so we cannot modify the props from inside the component. These attributes are available in the class component as **this.props** and can be used to render dynamic data in our render method.\n\n**Example:**\n\n```js\nfunction Welcome(props) {\n  return \u003ch1\u003eHello, {props.name}\u003c/h1\u003e;\n}\n\nconst element = \u003cWelcome name=\"World!\" /\u003e;\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-props-2k0081?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why props in React are read only?\n\nWhen you declare a component as a function or a class, it must never modify its own props.\n\nConsider this sum function:\n\n```js\nfunction sum(a, b) {\n  return a + b;\n}\n```\n\nSuch functions are called **pure** because they do not attempt to change their inputs, and always return the same result for the same inputs. All React components must act like pure functions with respect to their props. A component should only manage its own state, but it should not manage its own props.\n\nIn fact, props of a component is concretely \"the state of the another component (parent component)\". So props must be managed by their component owner. That\\'s why all React components must act like pure functions with respect to their props (not to mutate directly their props).\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/zYwPYwP?editors=1010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are default props?\n\nThe defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed.\n\nThe `defaultProps` can be defined as a property on the component class itself to set the default props for the class. `defaultProps` is used for **undefined** props, not for **null** props.\n\n```js\n/**\n * Default Props\n */\nclass MessageComponent extends React.Component {\n   render() {\n        return (\n          \u003cdiv\u003eHello, {this.props.value}.\u003c/div\u003e\n        )\n    }\n}\n\n// Default Props\nMessageComponent.defaultProps = {\n  value: 'World'  \n}\n\nReactDOM.render(\n  \u003cMessageComponent /\u003e, \n  document.getElementById('default')\n)\n\nReactDOM.render(\n  \u003cMessageComponent value='Folks'/\u003e, \n  document.getElementById('custom')\n)\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/oNWoNPm?editors=1010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to access props inside quotes in React JSX?\n\nReact JSX doesn\\'t support variable interpolation inside an attribute value, but we can put any JS expression inside curly braces as the entire attribute value.\n\n**Approach 1**: Putting js expression inside curly braces\n\n```js\n\u003cimg className=\"image\" src={\"images/\" + this.props.image} /\u003e\n```\n\n**Approach 2**: Using ES6 template literals.\n\n```js\n\u003cimg className=\"image\" src={`images/${this.props.image}`} /\u003e\n```\n\n**Example:**\n\n```js\n/**\n * Access Props\n */\nclass App extends Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cimg\n          alt=\"React Logo\"\n  \n          // Using ES6 template literals\n          src={`${this.props.image}`} \n        /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n  \nexport default App;\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/VwbrYwo)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to pass numbers to React component?\n\nIn react, numbers can be passed via curly braces(`{}`) where as strings in quotes (`\"\"`);\n\n**Example:**\n\n```js\nfunction App() {\n  return \u003cGreetings name=\"Nathan\" age={27} occupation=\"Software Developer\" /\u003e;\n}\n\n// Greetings Component\nfunction Greetings(props) {\n  return (\n    \u003ch2\u003e\n      Hello! I'm {props.name}, a {props.age} years old {props.occupation}.\n      Pleased to meet you!\n    \u003c/h2\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-number-props-tw1r1?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How are boolean props used in React?\n\nReact JSX has exactly two ways of passing true, `\u003cMyComponent prop /\u003e` and `\u003cMyComponent prop={true} /\u003e` and exactly one way of passing false `\u003cMyComponent prop={false} /\u003e`.\n\n**Example:**\n\n```js\n/**\n * Boolean Props\n */\nconst MyComponent = ({ prop1, prop2 }) =\u003e (\n  \u003cdiv\u003e\n    \u003cdiv\u003eProp1: {String(prop1)}\u003c/div\u003e\n    \u003cdiv\u003eProp2: {String(prop2)}\u003c/div\u003e\n  \u003c/div\u003e\n) \n\nfunction App() {\n  return (\n    \u003cdiv\u003e\n      \u003cMyComponent prop1={true} prop2={false} /\u003e\n      \u003cMyComponent prop1 prop2 /\u003e\n      \u003cMyComponent prop1={false} prop2 /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/abWVzJx)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to apply validation on Props in React?\n\nProps are an important mechanism for passing the **read-only** attributes to React components. React provides a way to validate the props using `PropTypes`. This is extremely useful to ensure that the components are used correctly.\n\n**Example:**\n\n```js\n/**\n * Props Validation\n */\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n\nexport default class App extends React.Component {\n  render() {\n    return (\n      \u003c\u003e\n        \u003ch3\u003eBoolean: {this.props.propBool ? \"True\" : \"False\"}\u003c/h3\u003e\n        \u003ch3\u003eArray: {this.props.propArray}\u003c/h3\u003e\n        \u003ch3\u003eNumber: {this.props.propNumber}\u003c/h3\u003e\n        \u003ch3\u003eString: {this.props.propString}\u003c/h3\u003e\n      \u003c/\u003e\n    );\n  }\n}\n\nApp.defaultProps = {\n  propBool: true,\n  propArray: [10, 20, 30],\n  propNumber: 100,\n  propString: \"Hello React!\"\n};\n\nApp.propTypes = {\n  propBool: PropTypes.bool.isRequired,\n  propArray: PropTypes.array.isRequired,\n  propNumber: PropTypes.number,\n  propString: PropTypes.string\n};\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-proptypes-41qmyz?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to specify the shape of an object with PropTypes\n\nThe `PropTypes.shape()` validator can be used when describing an object whose keys are known ahead of time, and may represent different types.\n\n**Example:**\n\n```js\n/**\n * PropTypes.shape()\n * @param {*} props\n */\nimport PropTypes from \"prop-types\";\n\nconst Component = (props) =\u003e (\n  \u003cdiv\u003e\n    Component badge: {props.badge ? JSON.stringify(props.badge) : \"none\"}\n  \u003c/div\u003e\n);\n\n// PropTypes validation for the prop object\nComponent.propTypes = {\n  badge: PropTypes.shape({\n    src: PropTypes.string.isRequired,\n    alt: PropTypes.string.isRequired\n  })\n};\n\nconst App = () =\u003e (\n  \u003cdiv\u003e\n    \u003cComponent badge={{ src: \"horse.png\", alt: \"Running Horse\" }} /\u003e\n    {/*\u003cComponent badge={{src:null, alt: 'this one gives an error'}}/\u003e*/}\n    \u003cComponent /\u003e\n  \u003c/div\u003e\n);\n\nexport default App;\n```\n\nOutput:\n\n```js\nComponent badge: {\"src\":\"horse.png\",\"alt\":\"Running Horse\"}\nComponent badge: none\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-proptypes-khi20j?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How PropTypes.objectOf is different from PropTypes.shape?\n\nThe `PropTypes.objectOf()` validator is used when describing an object whose keys might not be known ahead of time, and often represent the same type.\n\n**Example:**\n\n```js\n/**\n * PropTypes\n */\nimport PropTypes from 'prop-types';\n\n// Expected prop object - dynamic keys (i.e. user ids)\nconst myProp = {\n  25891102: 'Shila Jayashri',\n  34712915: 'Employee',\n  76912999: 'shila.jayashri@email.com'\n};\n\n// PropTypes validation for the prop object\nMyComponent.propTypes = {\n  myProp: PropTypes.objectOf(PropTypes.number)\n};\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How React PropTypes allow different types for one prop?\n\nUsing `PropTypes.oneOfType()` says that a prop can be one of any number of types. For instance, a phone number may either be passed to a component as a string or an integer:\n\n```js\n/**\n * PropTypes.oneOfType()\n */\nconst Component = (props) =\u003e \u003cdiv\u003ePhone Number: {props.phoneNumber}\u003c/div\u003e\n\nComponent.propTypes = {\n  phoneNumber: PropTypes.oneOfType([\n     PropTypes.number,\n     PropTypes.string\n  ]),\n}\n\nconst App = () =\u003e (\n  \u003cdiv\u003e\n    \u003cComponent phoneNumber={04403472916}/\u003e\n    {/*\u003cComponent phoneNumber={\"2823788557\"}/\u003e*/}\n  \u003c/div\u003e\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/LYyOmdP?editors=0011)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are render props?\n\nThe term **render props** refers to a technique for sharing code between React components using a prop whose value is a function.\n\nIn simple words, render props are simply props of a component where you can pass functions. These functions need to return elements, which will be used in rendering the components.\n\n**Example:**\n\n```js\n/**\n * Render Props\n */\nimport React from \"react\";\nimport Wrapper from \"./Wrapper\";\n\nclass App extends React.Component {\n  render() {\n    return (\n      \u003cWrapper\n        render={({ increment, count }) =\u003e (\n          \u003cdiv\u003e\n            \u003ch3\u003eRender Props Counter\u003c/h3\u003e\n            \u003cp\u003e{count}\u003c/p\u003e\n            \u003cbutton onClick={() =\u003e increment()}\u003eIncrement\u003c/button\u003e \n          \u003c/div\u003e\n        )}\n      /\u003e\n    );\n  }\n}\n```\n\n```js\n/**\n * Wrapper Component\n */\nclass Wrapper extends React.Component {\n  state = {\n    count: 0\n  };\n\n  // Increase count\n  increment = () =\u003e {\n    const { count } = this.state;\n    return this.setState({ count: count + 1 });\n  };\n\n  render() {\n    const { count } = this.state;\n\n    return (\n      \u003cdiv\u003e\n        {this.props.render({ increment: this.increment, count: count })}\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-render-props-c80gs?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the benefits of using Render Props?\n\n**Benefits:**\n\n* Reuse code across components when using ES6 classes.\n* The lowest level of indirection - it\\'s clear which component is called and the state is isolated.\n* No naming collision issues for props, state and class methods.\n* No need to deal with boiler code and hoisting static methods.\n\n**Problems:**\n\n* Caution using **`shouldComponentUpdate()`** as the render prop might close over data it is unaware of.\n* There could also be minor memory issues when defining a closure for every render. But be sure to measure first before  making performance changes as it might not be an issue for your app.\n* Another small annoyance is the render props callback is not so neat in JSX as it needs to be wrapped in an expression.  Rendering the result of an HOC does look cleaner.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you create Higher Order Component using render props?\n\nIt is possible to implement most higher-order components (HOC) using a regular component with a render prop. This way render props gives the flexibility of using either pattern.\n\n**Example:**\n\n```js\nfunction withMouse(Component) {\n  return class extends React.Component {\n    render() {\n      return (\n        \u003cMouse render={mouse =\u003e (\n          \u003cComponent {...this.props} mouse={mouse} /\u003e\n        )}/\u003e\n      );\n    }\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain HOC vs render props in react.js?\n\nThe Higher-Order Components, Render Props and Hooks are three patterns to implement **state-** or **behaviour*-** sharing between components. All three have their own use cases and none of them is a full replacement of the others.\n\n**1. Higher-order components:**\n\nEssentially HOC are similar to the decorator pattern, a function that takes a component as the first parameter and returns a new component. This is where you apply your crosscutting functionality.\n\n**Example:**\n\n```js\nfunction withExample(Component) {\n  return function(props) {\n    // cross cutting logic added here\n    return \u003cComponent {...props} /\u003e;\n  };\n}\n```\n\n**2. Render Props:**\n\nA render prop is where a component\\'s prop is assigned a function and this is called in the render method of the component. Calling the function can return a React element or component to render.\n\n**Example:**\n\n```js\nrender(){\n  \u003cFetchData render={(data) =\u003e {\n    return \u003cp\u003e{data}\u003c/p\u003e\n  }} /\u003e\n}\n```\n\nThe React community is moving away from HOC (higher order components) in favor of render prop components (RPC). For the most part, HOC and render prop components solve the same problem. However, render prop components provide are gaining popularity because they are more declarative and flexible than an HOC.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is children props?\n\nThe `{this.props.children}` is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component.\n\n**Example:**\n\n```js\n/**\n * React Children Props\n */\nclass MyComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eReact Children Props Example\u003c/h1\u003e\n        {this.props.children}\n      \u003c/div\u003e\n    );\n  }\n}\n\nclass OtherComponent extends React.Component {\n  render() {\n    return \u003cdiv\u003eOther Component Props\u003c/div\u003e;\n  }\n}\n\nReactDOM.render(\n  \u003cMyComponent\u003e\n    \u003cp\u003eReact DOM Props\u003c/p\u003e {/* Children Props*/}\n    \u003cOtherComponent /\u003e\n  \u003c/MyComponent\u003e,\n  document.getElementById(\"root\")\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-children-props-952wx?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When we should use React.cloneElement vs this.props.children?\n\nThe `React.cloneElement()` works if child is a single React element.\n\nFor almost everything `{this.props.children}` is used. Cloning is useful in some more advanced scenarios, where a parent sends in an element and the child component needs to change some props on that element or add things like `ref` for accessing the actual DOM element.\n\n**React.Children:**  \n\nSince `{this.props.children}` can have one element, multiple elements, or none at all, its value is respectively a single child node, an array of child nodes or undefined. Sometimes, we want to transform our children before rendering them — for example, to add additional props to every child. If we wanted to do that, we\\'d have to take the possible types of `this.props.children` into account. For example, if there is only one child, we can not map it.\n\n**Example:**\n\n```js\n/**\n * React Children Props\n */\nexport default class App extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cb\u003eChildren ({this.props.children.length}):\u003c/b\u003e\n        {this.props.children}\n      \u003c/div\u003e\n    );\n  }\n}\n\nclass Widget extends React.Component {\n\n  render() {\n    return \n      \u003cdiv\u003e\n        \u003ch2\u003eFirst Example:\u003c/h2\u003e\n        \u003cApp\u003e\n          \u003cdiv\u003e10\u003c/div\u003e\n          \u003cdiv\u003e20\u003c/div\u003e\n          \u003cdiv\u003e30\u003c/div\u003e\n        \u003c/App\u003e\n        \u003ch2\u003eSecond Example:\u003c/h2\u003e\n        \u003cApp\u003e\n          \u003cdiv\u003eA\u003c/div\u003e\n          \u003cdiv\u003eB\u003c/div\u003e\n        \u003c/App\u003e\n      \u003c/div\u003e\n  }\n}\n```\n\nOutput\n\n```js\nFirst Example:\nChildren (3):\n10\n20\n30\n\nSecond Example:\nChildren (2):\nA\nB\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-children-props-7ry7cc?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do these three dots in React do?\n\nThe ES6 Spread operator or Rest Parameters is use to pass `props` to a React component. Let us take an example for a component that expects two props:\n\n```js\nfunction App() {\n  return \u003cHello firstName=\"Pallav\" lastName=\"Hegde\" /\u003e\n}\n```\n\nUsing the Spread operator, it become like this\n\n```js\nfunction App() {\n  const props = {firstName: 'Pallav', lastName: 'Hegde'}\n  return \u003cHello {...props} /\u003e\n}\n```\n\nWhen we use the `...props` syntax, actaully it expand the props object from the parent component, which means all its attributes are passed down the child component that may not need them all. This will make things like debugging harder.\n\n**Using the Spread Operator with setState() for Setting the Nested State:**\n\nLet us suppose we have a state with a nested object in our component:\n\n```js\nthis.state = {\n  stateObj: {\n    attr1: '',\n    attr2: '',\n  },\n}\n```\n\nWe can use the Spread syntax to update the nested state object.\n\n```js\nthis.setState(state =\u003e ({\n  person: {\n    ...state.stateObj,\n    attr1: 'value1',\n    attr2: 'value2',\n  },\n}))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why we need to be careful when spreading props on DOM elements?\n\nWhen we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice.\n\n**Problem:** This will try to add the unknown HTML attribute `flag` to the DOM element.\n\n```js\nconst Sample = () =\u003e (\u003cSpread flag={true} className=\"content\"/\u003e);\nconst Spread = (props) =\u003e (\u003cdiv {...props}\u003eTest\u003c/div\u003e);\n```\n\n**Solution:** By creating props specifically for DOM attribute, we can safely spread.\n\n```js\nconst Sample = () =\u003e (\u003cSpread flag={true} domProps={{className: \"content\"}}/\u003e);\nconst Spread = (props) =\u003e (\u003cdiv {...props.domProps}\u003eTest\u003c/div\u003e);\n```\n\nOr alternatively we can use prop destructuring with `...rest`:\n\n```js\nconst Sample = () =\u003e (\u003cSpread flag={true} className=\"content\"/\u003e);\nconst Spread = ({ flag, ...domProps }) =\u003e (\u003cdiv {...domProps}\u003eTest\u003c/div\u003e);\n```\n\n**Note:**\n\n*In scenarios where you use a PureComponent, when an update happens it re-renders the component even if domProps did not change. This is because PureComponent only shallowly compares the objects.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What will happen if you use props in initial state?\n\nUsing props to generate state in `getInitialState` often leads to duplication of \"source of truth\", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.\n\nThe danger is that if the `props` on the component are changed without the component being *'refreshed'*, the new prop value will never be displayed because the constructor function (or getInitialState) will never update the current state of the component. The initialization of state from `props` only runs when the component is first created.\n\n**Bad:**\n\nThe below component won\\'t display the updated input value\n\n```js\nclass App extends React.Component {\n\n  // constructor function (or getInitialState)\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      records: [],\n      inputValue: this.props.inputValue\n    }\n  }\n\n  render() {\n    return \u003cdiv\u003e{this.state.inputValue}\u003c/div\u003e\n  }\n}\n```\n\n**Good:**\n\nUsing props inside render method will update the value:\n\n```js\nclass App extends React.Component {\n\n  // constructor function (or getInitialState)\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      records: []\n    }\n  }\n\n  render() {\n    return \u003cdiv\u003e{this.props.inputValue}\u003c/div\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between createElement and cloneElement?\n\nJSX elements will be transpiled to `React.createElement()` functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.\n\nThe `React.cloneElement()` function returns a copy of a specified element. Additional props and children can be passed on in the function. We shoul use this function when a parent component wants to add or modify the `props` of its children.\n\n```js\nimport React from 'react'\n\nexport default class App extends React.Component {\n  // rendering the parent and child component\n  render() {\n    return (\n      \u003cParentComp\u003e\n        \u003cMyButton/\u003e\n        \u003cbr/\u003e\n        \u003cMyButton/\u003e\n      \u003c/ParentComp\u003e\n    )\n  }\n}\n\n/**\n * The parent component\n */\nclass ParentComp extends React.Component {\n  render() {\n    // The new prop to the added.\n    let newProp = 'red'\n      // Looping over the parent's entire children,\n      // cloning each child, adding a new prop.\n    return (\n      \u003cdiv\u003e\n        {React.Children.map(this.props.children,\n          child =\u003e {\n            return React.cloneElement(child,\n            {newProp}, null)\n        })}\n      \u003c/div\u003e\n    )\n  }\n}\n\n/**\n * The child component\n */\nclass MyButton extends React.Component {\n  render() {\n    return \u003cbutton style =\n    {{ color: this.props.newProp }}\u003e\n    Hello World!\u003c/button\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When should I be using React.cloneElement vs this.props.children?\n\nThe `React.cloneElement` only works if your child is a single React element.\n\n**Example:**\n\n```js\n\u003cReactCSSTransitionGroup\n     component=\"div\"\n     transitionName=\"example\"\n     transitionEnterTimeout={500}\n     transitionLeaveTimeout={500}\n     \u003e\n     {React.cloneElement(this.props.children, {\n       key: this.props.location.pathname\n      })}\n\u003c/ReactCSSTransitionGroup\u003e\n```\n\nFor almost everything `{this.props.children}` is used. Cloning is useful in some more advanced scenarios, where a parent sends in an element and the child component needs to change some props on that element or add things like `ref` for accessing the actual DOM element.\n\n**Example:**\n\n```js\nclass Users extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch2\u003eUsers\u003c/h2\u003e\n        {this.props.children}\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to pass JSON Objects from Child to Parent Component?\n\n**Using callback function:** \n\n```js\n/**\n * Parent Component\n */\nexport default class App extends React.Component {\n  constructor() {\n    super();\n    this.state = {\n      message: \"\"\n    };\n    this.onSubmitMessage = this.onSubmitMessage.bind(this);\n  }\n\n  onSubmitMessage(message) {\n    this.setState({ message: message });\n  }\n\n  render() {\n    const { message } = this.state;\n\n    return (\n      \u003cdiv\u003e\n        \u003ch3\u003eParent component\u003c/h3\u003e\n        \u003cdiv\u003eThe message coming from the child component is : {message}\u003c/div\u003e\n        \u003chr /\u003e\n        \u003cChild\n          // passing as callback function\n          onSubmitMessage={this.onSubmitMessage}\n        /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n```js\n/**\n * Child Component\n */\nexport default class Child extends React.Component {\n  constructor() {\n    super();\n    this.state = {\n      greetingMessag: \"\"\n    };\n    this.onMessageChange = this.onMessageChange.bind(this);\n    this.onSubmit = this.onSubmit.bind(this);\n  }\n\n  onMessageChange(event) {\n    let message = event.target.value;\n    this.setState({ greetingMessag: message });\n  }\n\n  // pass message to parent component using callback\n  onSubmit() {\n    this.props.onSubmitMessage(this.state.greetingMessag);\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch3\u003eChild Component\u003c/h3\u003e\n        \u003cinput\n          type=\"text\"\n          onChange={this.onMessageChange}\n          placeholder=\"Enter a message\"\n        /\u003e\n        \u003cbutton onClick={this.onSubmit}\u003eSubmit\u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-callback-function-i2wv6?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the use of this props?\n\nIt is called spread operator (ES6 feature) and its aim is to make the passing of props easier.\n\n**Example:**\n\n```js\n\u003cdiv {...this.props}\u003e\n  Content Here\n\u003c/div\u003e\n```\n\nIt is equal to Class Component\n\n```js\nconst person = {\n    name: \"Alex\",\n    age: 26,\n    country: \"India\"\n}\n\nclass SpreadExample extends React.Component {\n    render() {\n      const {name, age, country} = {...this.props}\n      return (\n        \u003cdiv\u003e\n            \u003ch3\u003e Person Information: \u003c/h3\u003e\n            \u003cul\u003e\n              \u003cli\u003ename={name}\u003c/li\u003e\n              \u003cli\u003eage={age}\u003c/li\u003e\n              \u003cli\u003ecountry={country}\u003c/li\u003e\n            \u003c/ul\u003e\n        \u003c/div\u003e\n      )\n    }\n}\n\nReactDOM.render(\n    \u003cSpreadExample {...person}/\u003e\n    , mountNode\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 6. REACT STATE\n\n\u003cbr/\u003e\n\n## Q. What is State in React?\n\nThe state is a built-in object that is used to contain data about the component. A component\\'s state can change over time; whenever it changes, the component re-renders.\n\n**Example:**\n\n```js\n/**\n * React State\n */\nexport default class Employee extends React.Component {\n  constructor() {\n    super();\n    this.state = {\n      id: 100,\n      name: \"Sarita Mangat\"\n    };\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cdiv\u003eID: {this.state.id}\u003c/div\u003e\n        \u003cdiv\u003eName: {this.state.name}\u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-state-8d815y?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What does setState() do?\n\nThe component state can be updated in response to event handlers, server responses, or prop changes. This is done using the **setState()** method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.\n\nAlways use the setState() method to change the state object, since it will ensure that the component knows it\\'s been updated and calls the `render()` method.\n\n**Example:**\n\n```js\n/**\n * React setState()\n */\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      color: \"blue\"\n    };\n  }\n\n  handleColor = () =\u003e {\n    this.setState({ color: \"red\" });\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch3\u003eColor: {this.state.color}\u003c/h3\u003e\n\n        \u003cbutton type=\"button\" onClick={this.handleColor}\u003e\n          Change Color\n        \u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-setstate-d58xff?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why is setState() in React async instead of sync?\n\nThe **setState()** does not immediately mutate `this.state()` but creates a pending state transition. Accessing `this.state()` after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState() and calls may be batched for performance gains.\n\nThis is because setState() alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus the setState() calls are asynchronous as well as batched for better UI experience and performance.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the second argument that can optionally be passed to setState() and what is its purpose?\n\nA **callback function** which will be invoked when `setState()` has finished and the component is re-rendered. The setState() is asynchronous, which is why it takes in a second callback function. Typically it\\'s best to use another lifecycle method rather than relying on this callback function, but it is good to know it exists.\n\n**Example:**\n\n```js\nthis.setState(\n  { username: 'Lila' },\n  () =\u003e console.log('setState has finished and the component has re-rendered.')\n)\n```\n\nThe setState() will always lead to a re-render unless `shouldComponentUpdate()` returns **false**. To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like `componentDidUpdate()`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the possible ways of updating objects in state?\n\nInstead of directly modifying the state using `this.state()`, we use `this.setState()`. This is a function available to all React components that use state, and allows us to let React know that the component state has changed. This way the component knows it should re-render, because its state has changed and its UI will most likely also change.\n\n**Example:**\n\n```js\nthis.state = {\n  user: { name: 'Vasuda Handa', age: 22 }\n}\n```\n\n* **Using Object.assign()**\n\n```js\nthis.setState(prevState =\u003e {\n  let user = Object.assign({}, prevState.user);  // creating copy of state variable user\n  user.name = 'Sai Gupta';                            // update the name property, assign a new value\n  return { user };                                 // return new object user object\n})\n```\n\n* **Using spread syntax**\n\n```js\nthis.setState(prevState =\u003e ({\n    user: {                   // object that we want to update\n        ...prevState.user,    // keep all other key-value pairs\n        name: 'Niraj Gara'       // update the value of specific key\n    }\n}))\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/abWVaKr?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What will happen if you use setState() in constructor?\n\nWhen we use `setState()`, then apart from assigning to the object state react also rerenders the component and all it\\'s children. Which we don\\'t need in the constructor, since the component hasn\\'t been rendered anyway.\n\nInside constructor uses `this.state = {}` directly, other places use `this.setState({ })`\n\n**Example:**\n\n```js\nimport React, { Component } from 'react'\n\nclass Food extends Component {\n\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      fruits: ['apple', 'orange'],\n      count: 0\n    }\n  }\n  render() {\n    return (\n      \u003cdiv className = \"container\"\u003e\n        \u003ch2\u003e Hello!!!\u003c/h2\u003e\n        \u003cp\u003e I have {this.state.count} fruit(s)\u003c/p\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/bGWYmBK?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why should not we update the state directly?\n\nThe **setState()** does not immediately mutate `this.state()` but creates a pending state transition. Accessing `this.state()` after calling this method can potentially return the existing value.\n\nThe setState() will always trigger a re-render unless conditional rendering logic is implemented in **shouldComponentUpdate()**. If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.\n\n**Example:**\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      list: [\n        { id: '1', age: 42 },\n        { id: '2', age: 33 },\n        { id: '3', age: 68 },\n      ],\n    }\n  }\n\n  onRemoveItem = id =\u003e {\n    this.setState(state =\u003e {\n      const list = state.list.filter(item =\u003e item.id !== id)\n\n      return {\n        list,\n      }\n    })\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cul\u003e\n          {this.state.list.map(item =\u003e (\n            \u003cli key={item.id}\u003e\n              The person is {item.age} years old.\n              \u003cbutton\n                type=\"button\"\n                onClick={() =\u003e this.onRemoveItem(item.id)}\n              \u003e\n                Remove\n              \u003c/button\u003e\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default App\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/mdmqzmB?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to delete an item from state array?\n\nWhen using React, we should never mutate the state directly. If an object is changed, we should create a new copy. The better approach is to use `Array.prototype.filter()` method which creates a new array.\n\n**Example:**\n\n```js\nonDeleteByIndex(index) {\n  this.setState({\n    users: this.state.users.filter((item, i) =\u003e i !== index)\n  });\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/vYmWvZE?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why should not call setState() in componentWillUnmount()?\n\nWe should not call `setState()` in `componentWillUnmount()` because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.\n\nThe `componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. This method can be used to perform any necessary cleanup method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in `componentDidMount()`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can you re-render a component without using setState() function?\n\nReact components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.\n\nHowever, there may be cases where the render() method depends on some other data. After the initial mounting of components, a re-render will occur.\n\n**Using forceUpdate():**\n\nThe following example generates a random number whenever it loads. Upon clicking the button, the `forceUpdate()` function is called which causes a new, random ​number to be rendered:\n\n```js\n/**\n * forceUpdate()\n */\nexport default class App extends React.Component {\n  constructor(){\n    super();\n    this.forceUpdateHandler = this.forceUpdateHandler.bind(this);\n  };\n  \n  forceUpdateHandler(){\n    this.forceUpdate();\n  };\n  \n  render(){\n    return(\n      \u003cdiv\u003e\n        \u003cbutton onClick= {this.forceUpdateHandler} \u003eFORCE UPDATE\u003c/button\u003e\n        \u003ch4\u003eRandom Number : { Math.random() }\u003c/h4\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/ZEKaqWN?editors=0010)**\n\n*Note: We should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in render().*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why we need to pass a function to setState()?\n\nThe reason behind for this is that `setState()` is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after `setState()` is called. That means we should not rely on the current state when calling `setState()`.\n\nThe solution is to **pass a function to setState()**, with the previous state as an argument. By doing this we can avoid issues with the user getting the old state value on access due to the asynchronous nature of `setState()`.\n\n**Problem:**\n\n```js\n// assuming this.state.count === 0\nthis.setState({count: this.state.count + 1});\nthis.setState({count: this.state.count + 1});\nthis.setState({count: this.state.count + 1});\n// this.state.count === 1, not 3\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/jOmYEGG?editors=0010)**\n\n**Solution:**\n\n```js\nthis.setState((prevState) =\u003e ({\n  count: prevState.count + 1\n}));\nthis.setState((prevState) =\u003e ({\n  count: prevState.count + 1\n}));\nthis.setState((prevState) =\u003e ({\n  count: prevState.count + 1\n}));\n// this.state.count === 3 as expected\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/qBmpEoz?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to update nested state properties in React.js?\n\nWe can pass the old nested object using the spread operator and then override the particular properties of the nested object.\n\n**Example:**\n\n```js\n// Nested object\nstate = {\n  name: 'Vyasa Agarwal',\n  address: {\n    colony: 'Old Cross Rds, Mehdipatnam',\n    city: 'Patna',\n    state: 'Jharkhand'\n  }\n};\n  \nhandleUpdate = () =\u003e {\n  // Overriding the city property of address object\n  this.setState({ address: { ...this.state.address, city: \"Ranchi\" } })\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/VwbyYqv?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between state and props?\n\n|Props                             |State                             |\n|----------------------------------|----------------------------------|\n|Props are read-only.              |State changes can be asynchronous.|\n|Props are immutable.              |State is mutable.                 |\n|Props allow you to pass data from one component to other components as an argument.|\tState holds information about the components.|\n|Props can be accessed by the child component.    |State cannot be accessed by child components.|\n|Props are used to communicate between components.|States can be used for rendering dynamic changes with the component.|\n|Stateless component can have Props.            |Stateless components cannot have State.|\n|Props make components reusable.                 |State cannot make components reusable.|\n|Props are external and controlled by whatever renders the component.|The State is internal and controlled by the React Component itself.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set state with a dynamic key name?\n\nIf you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with *computed property* names.\n\n```js\ninputChangeHandler : function (event) {\n  this.setState({ [event.target.id]: event.target.value });\n\n  // alternatively using template strings for strings\n  // this.setState({ [`key${event.target.id}`]: event.target.value });\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/QWvayKp?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to listen state change in React.js?\n\nThe following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.\n\n```js\ncomponentWillUpdate(object nextProps, object nextState)\ncomponentDidUpdate(object prevProps, object prevState)\n```\n\nIn functional component, listen state changes with useEffect hook like this\n\n```js\nexport function MyComponent(props) {\n    const [myState, setMystate] = useState('initialState')\n\n    useEffect(() =\u003e {\n        console.log(myState, '- Has changed')\n    },[myState]) // \u003c-- here put the parameter to listen\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to access child\\'s state in React?\n\n**Using Refs:**\n\nIn React we can access the child\\'s state using `React.createRef()`. We will assign a Refs for the child component in the parent component, then using Refs we can access the child\\'s state.\n\n```js\n// App.js\n\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.ChildElement = React.createRef();\n  }\n  handleClick = () =\u003e {\n    const childelement = this.ChildElement.current;\n    childelement.getMsg(\"Message from Parent Component!\");\n  };\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cChild ref={this.ChildElement} /\u003e\n        \u003cbutton onClick={this.handleClick}\u003eCLICK ME\u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n```js\n// Child.js\n\nclass Child extends React.Component {\n  state = {\n    name: \"Message from Child Component!\"\n  };\n  getMsg = (msg) =\u003e {\n    this.setState({\n      name: msg\n    });\n  };\n  render() {\n    return \u003ch2\u003e{this.state.name}\u003c/h2\u003e;\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-access-childs-state-n5uzr)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to change the state of a child component from its parent in React?\n\nTo change child component\\'s state from parent component with React, we can pass props.\n\n```js\n/**\n * Change Child state from its Parent\n * @param {*} param0\n */\nconst Child = ({ open }) =\u003e {\n  return \u003ch2\u003eChild State: {open.toString()}\u003c/h2\u003e;\n};\n\nconst Parent = () =\u003e {\n  const [isOpen, setIsOpen] = React.useState(false);\n\n  const toggleChild = () =\u003e {\n    setIsOpen((prevValue) =\u003e !prevValue);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={toggleChild}\u003eClick Me\u003c/button\u003e\n      {/* Pass a callback to Child */}\n      \u003cChild open={isOpen} /\u003e\n    \u003c/div\u003e\n  );\n};\n\nexport default Parent;\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/agitated-aryabhata-26wdz5?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why is it advised to pass a callback function to setState() as opposed to an object?\n\nBecause `this.props` and `this.state` may be updated asynchronously, we should not rely on their values for calculating the next state.\n\n**Example**: setState Callback in a Class Component\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n  constructor(props) {\n    super(props)\n    this.state = {\n      age: 0,\n    }\n  }\n  \n  // this.checkAge is passed as the callback to setState\n  updateAge = (value) =\u003e {\n    this.setState({ age: value}, this.checkAge)\n  }\n\n  checkAge = () =\u003e {\n    const { age } = this.state\n    if (age !== 0 \u0026\u0026 age \u003e= 21) {\n      // Make API call to /beer\n    } else {\n      // Throw error 404, beer not found\n    }\n  }\n\n  render() {\n    const { age } = this.state\n    return (\n      \u003cdiv\u003e\n        \u003cp\u003eDrinking Age Checker\u003c/p\u003e\n        \u003cinput\n          type=\"number\"\n          value={age}\n          onChange={e =\u003e this.updateAge(e.target.value)}\n        /\u003e\n      \u003c/div\u003e\n    )\n  }\n}\nexport default App\n```\n\n**Example:** setState Callback in a Functional Component\n\n```js\nimport React, { useEffect, useState } from 'react'\n\nfunction App() {\n  const [age, setAge] = useState(0)\n  \n  updateAge(value) {\n    setAge(value)\n  }\n\n  useEffect(() =\u003e {\n    if (age !== 0 \u0026\u0026 age \u003e= 21) {\n      // Make API call to /beer\n    } else {\n      // Throw error 404, beer not found\n    }\n  }, [age])\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eDrinking Age Checker\u003c/p\u003e\n      \u003cinput\n        type=\"number\"\n        value={age} \n        onChange={e =\u003e setAge(e.target.value)}\n      /\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default App\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does the state differ from props in React?\n\n**1. State:**\n\nThis is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the `setState()` function.\n\n**Example:**\n\n```js\nclass AppComponent extends React.component {\n  state = {\n      msg : 'Hello World!'\n  }\n\n  render() {\n      return \u003cdiv\u003eMessage {this.state.msg}\u003c/div\u003e\n  }\n}\n```\n\n**2. Props:**\n\nData passed in from a parent component. `props` are read-only in the child component that receives them. However, callback functions can also be passed, which can be executed inside the child to initiate an update.\n\n**Example:** The parent can pass a props by using this\n\n```js\n\u003cChildComponent color='red' /\u003e\n```\n\nInside the ChildComponent constructor we could access the props\n\n```js\nclass ChildComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    console.log(props.color)\n  }\n}\n```\n\nProps can be used to set the internal state based on a prop value in the constructor, like this\n\n```js\nclass ChildComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state.colorName = props.color\n  }\n}\n```\n\nProps should never be changed in a child component. Props are also used to allow child components to access methods defined in the parent component. This is a good way to centralize managing the state in the parent component, and avoid children to have the need to have their own state.\n\n**Difference between State and Props:**\n\n|  Props                                          | State                            |\n|-------------------------------------------------|----------------------------------|\n|Props are read-only.                             |State changes can be asynchronous.|\n|Props allow to pass data from one component to other components as an argument.| State holds information about the components.|\n|Props can be accessed by the child component.    |State cannot be accessed by child components.|\n|Props are used to communicate between components.|States can be used for rendering dynamic changes with the component.|\n|Stateless component can have Props.              |Stateless components cannot have State.|\n|Props are external and controlled by whatever renders the component.| The State is internal and controlled by the React Component itself.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 7. REACT EVENTS\n\n\u003cbr/\u003e\n\n## Q. What is meant by event handling in React?\n\nHandling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:\n\n* React events are named using camelCase, rather than lowercase.\n* With JSX you pass a function as the event handler, rather than a string.\n\n**Example:**\n\n```js\n/**\n * Event Handling in React\n */\nexport default class Toggle extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { isToggleOn: true };\n  }\n\n  handleClick() {\n    this.setState((state) =\u003e ({\n      isToggleOn: !state.isToggleOn\n    }));\n  }\n\n  render() {\n    return (\n      \u003cbutton onClick={() =\u003e this.handleClick()}\u003e\n        {this.state.isToggleOn ? \"ON\" : \"OFF\"}\n      \u003c/button\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-event-handling-coshzh?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to pass a parameter to event handlers in React?\n\n**Example:**\n\n```js\nconst message = \"Hey there!\";\nexport default class App extends React.Component {\n  displayMessage(message) {\n    alert(message);\n  }\n\n  render() {\n    return (\n      \u003cbutton onClick={() =\u003e this.displayMessage(message)}\u003eCLICK ME\u003c/button\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-event-handler-g2ugs?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you pass an event handler to a component?\n\n**Example:**\n\n```js\nimport React, {useState} from \"react\";\nimport \"./styles.css\";\n\nexport default function App() {\n  return (\n    \u003cContainer/\u003e\n  );\n}\n\nconst Container = () =\u003e {\n  const [counter, setCounter] = useState(0);\n  \n  const handleCustomClick = () =\u003e {\n    setCounter(counter + 1)\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv\u003eCounter: {counter}\u003c/div\u003e\n      \u003cCustomButton onCustomClick={handleCustomClick}/\u003e\n    \u003c/div\u003e\n  );\n}\n\nconst CustomButton = ({onCustomClick}) =\u003e {\n  return (\n    \u003cbutton onClick={onCustomClick}\u003e\n      My Custom Button\n    \u003c/button\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-event-handler-ijru1?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between HTML and React event handling?\n\nIn HTML, the attribute name is in all lowercase and is given a string invoking a function defined somewhere:\n\n```js\n\u003cbutton onclick=\"handleClick()\"\u003e\u003c/button\u003e\n```\n\nIn React, the attribute name is camelCase and are passed the function reference inside curly braces:\n\n```js\n\u003cbutton onClick={handleClick} /\u003e\n```\n\nIn HTML, `false` can be returned to prevent default behavior, whereas in React `preventDefault()` has to be called explicitly.\n\n```js\n\u003ca href=\"#\" onclick=\"console.log('The link was clicked.'); return false\" /\u003e\n\nfunction handleClick(e) {\n  e.preventDefault()\n  console.log(\"The link was clicked.\")\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to bind methods or event handlers in JSX callbacks?\n\nThere are 3 possible ways to achieve this\n\n**1. Event Handler in Render Method:**\n\nWe can bind the handler when it is called in the render method using `bind()` method.\n\n```js\nhandleClick() {\n  // ...       \n}\n\n\u003cbutton onClick={this.handleClick.bind(this)}\u003eClick\u003c/button\u003e \n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/jOmYGMp?editors=0010)**\n\n**2. Event Handler using Arrow Function:**\n\nIn this approach we are binding the event handler implicitly. This approach is the best if you want to pass parameters to your event.\n\n```js\nhandleClick() {\n  // ...       \n}\n\n\u003cbutton onClick={() =\u003e this.handleClick()}\u003eClick\u003c/button\u003e \n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/QWvaqdB?editors=0010)**\n\n**3. Event Handler in Constructor:**\n\nThis has performance benefits as the events aren\\'t binding every time the method is called, as opposed to the previous two approaches.\n\n```js\nconstructor(props) {\n\n  // This binding is necessary to make `this` work in the callback\n  this.handleClick = this.handleClick.bind(this);\n}\n\nhandleClick() {\n  // ...       \n}\n\n\u003cbutton onClick={this.handleClick}\u003eClick\u003c/button\u003e\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/zYwpEwO?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why do we need to bind methods inside class component constructor?\n\nIn Class Components, when we pass the event handler function reference as a callback like this\n\n```js\n\u003cbutton type=\"button\" onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n```\n\nthe event handler method loses its **implicitly bound** context. When the event occurs and the handler is invoked, the `this` value falls back to **default binding** and is set to `undefined`, as class declarations and prototype methods run in strict mode.\n\nWhen we bind the `this` of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.\n\nArrow functions are exempt from this behavior because they use **lexical** `this` binding which automatically binds them to the scope they are defined in.\n\n**Example:**\n\n```js\n/**\n * Event Handling in React\n */\nimport React from \"react\";\n\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick(event) {\n    alert(\"Click event triggered!\");\n  }\n\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e;\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-event-handling-k0hugz?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do I pass a parameter to an event handler or callback?\n\nYou can use an **arrow function** to wrap around an event handler and pass parameters:\n\n```js\n\u003cbutton onClick={() =\u003e this.handleClick(id)} /\u003e\n```\n\nThis is equivalent to calling `.bind`\n\n```js\n\u003cbutton onClick={this.handleClick.bind(this, id)} /\u003e\n```\n\n**Example:**\n\n```js\n/**\n * Pass parameter to an event handler\n */\nconst A = 65; // ASCII character code\n\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      justClicked: null,\n      letters: Array.from({ length: 26 }, (_, i) =\u003e String.fromCharCode(A + i))\n    };\n  }\n\n  handleClick(letter) {\n    this.setState({ justClicked: letter });\n  }\n  \n  render() {\n    return (\n      \u003c\u003e\n        Just clicked: {this.state.justClicked}\n        \u003cul\u003e\n          {this.state.letters.map((letter) =\u003e (\n            \u003cli key={letter} onClick={() =\u003e this.handleClick(letter)}\u003e\n              {letter}\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-event-parameter-br87ji?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When should we use arrow functions with React?\n\n**Arrows prevent `this` bugs**\n\nArrow functions do not redefine the value of `this` within their function body. This makes it a lot easier to predict their behavior when passed as callbacks, and prevents bugs caused by use of this within callbacks. Using inline arrow functions in function components is a good way to achieve some decoupling.\n\n**Example:**\n\n```js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\n\nclass Button extends React.Component {\n  render() {\n    return (\n      \u003cbutton onClick={this.handleClick} style={this.state}\u003e\n        Set background to red\n      \u003c/button\u003e\n    )\n  }\n\n  handleClick = () =\u003e {\n    this.setState({ backgroundColor: 'red' })\n  }\n}\n\nReactDOM.render(\n  \u003cButton /\u003e,\n  document.getElementById('root')\n)\n```\n\n1. When we use `this` it generates a new function on every render, which will obviously have a new reference.\n2. If the component we pass this generated function to is extending `PureComponent()`, it will not be able to bail out on rerendering, even if the actual data has not changed.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Is it good to use arrow functions in render methods?\n\n**Problem:**\n\nThe **bind()** method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. When arrow functions and binds in render. It breaks performance optimizations like `shouldComponentUpdate()` and `PureComponent`.\n\n**Example:**\n\n```js\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n    ...\n  }\n\n  deleteUser = id =\u003e {\n    this.setState(prevState =\u003e {\n      return {\n        users: prevState.users.filter(user =\u003e user.id !== id)\n      };\n    });\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cul\u003e\n          {this.state.users.map(user =\u003e {\n            return (\n              \u003cUser key={user.id} name={user.name} id={user.id}\n                onDeleteClick={() =\u003e this.deleteUser(user.id)}\n              /\u003e\n            );\n          })}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-arrow-in-render-3d0x0)**\n\n**Solution:**\n\nIn below example, **App Component** has no arrow function in render. Instead, the relevant data is passed down to **User Component**. In User Component, `onDeleteClick()` calls the onClick function passed in on props with the relevant user.id.\n\n```js\n// User Component\n\nclass User extends React.PureComponent {\n  onDeleteClick = () =\u003e {\n    // No bind needed since we can compose the relevant data for this item here\n    this.props.onClick(this.props.user.id);\n  };\n\n  render() {\n    console.log(`${this.props.user.name} just rendered`);\n    return (\n      \u003cli\u003e\n        \u003cinput type=\"button\" value=\"Delete\" onClick={this.onDeleteClick} /\u003e\n        {this.props.user.name}\n      \u003c/li\u003e\n    );\n  }\n}\n```\n\n```js\n// App Component\n\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n    ...\n  }\n\n  deleteUser = id =\u003e {\n    this.setState(prevState =\u003e {\n      return { \n        users: prevState.users.filter(user =\u003e user.id !== id) \n      };\n    });\n  };\n\n  renderUser = user =\u003e {\n    return \u003cUser key={user.id} user={user} onClick={this.deleteUser} /\u003e;\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cul\u003e\n          {this.state.users.map(this.renderUser)}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-arrow-functions-v8yt7?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to avoid the need for binding in React?\n\n**1. Use Arrow Function in Class Property:**\n\nUsually when we want to access this inside a class method we would need to bind it to method like so:\n\n```js\nclass Button extends Component {\n  constructor(props) {\n    super(props)\n    this.state = { clicked: false }\n  }\n  handleClick = () =\u003e this.setState({ clicked: true })\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\nBinding `this` to `handleClick()` in the `constructor()` allows us to use `this.setState()` from Component inside `handleClick()`.\n\n**2. Bind in Render:**\n\n```js\nonChange={this.handleChange.bind(this)}\n```\n\nThis approach is terse and clear, however, there are performance implications since the function is reallocated on every render.\n\n**3. Bind in Constructor:**\n\nOne way to avoid binding in render is to bind in the constructor\n\n```js\nconstructor(props) {\n  super(props)\n  this.handleChange = this.handleChange.bind(this)\n}\n```\n\nThis is the approach currently recommended in the React docs for \"better performance in your application\".\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do I bind a function to a component instance?\n\nThere are several ways to make sure functions have access to component attributes like `this.props` and `this.state`, depending on which syntax and build steps you are using.\n\n**1. Bind in Constructor (ES5):**\n\n```js\nclass App extends Component {\n  constructor(props) {\n    super(props)\n    this.handleClick = this.handleClick.bind(this)\n  }\n  handleClick() {\n    console.log('Click happened')\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n**2. Class Properties:**\n\n```js\nclass App extends Component {\n  // Note: this syntax is experimental and not standardized yet.\n  handleClick = () =\u003e {\n    console.log('Click happened')\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n**3. Bind in Render:**\n\n```js\nclass App extends Component {\n  handleClick() {\n    console.log('Click happened')\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick.bind(this)}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n*Note: Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications*\n\n**4. Arrow Function in Render:**\n\n```js\nclass App extends Component {\n  handleClick() {\n    console.log('Click happened')\n  }\n  render() {\n    return \u003cbutton onClick={() =\u003e this.handleClick()}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n*Note: Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can I prevent a function from being called too quickly?\n\n**1. Throttle:**\n\nThrottling prevents a function from being called more than once in a given window of time.\n\n**2. Debounce:**\n\nDebouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events).\n\n**Example:**\n\n```js\n/**\n * Throttle and Debounce in React\n */\nimport * as React from \"react\";\nimport * as _ from \"lodash\";\n\nexport default class App extends React.Component {\n  state = { count: 0 };\n\n  handleCount() {\n    this.setState((state) =\u003e ({\n      count: state.count + 1\n    }));\n  }\n\n  // You will run count() only once after 100ms\n  handleDebounce = _.debounce(() =\u003e this.handleCount(), 100);\n\n  // You will run count() every 200ms\n  handleThrottle = _.throttle(() =\u003e this.handleCount(), 200);\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        {this.state.count}\n        \u003chr /\u003e\n        \u003cbutton onClick={this.handleThrottle}\u003eClick Me - Throttle \u003c/button\u003e\n        \u003cbutton onClick={this.handleDebounce}\u003eClick Me - Debounce \u003c/button\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-throttle-debounce-doch91?file=/src/App.js)**\n\n**3. RequestAnimationFrame Throttling:**\n\nThe **requestAnimationFrame** is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. A function that is queued with requestAnimationFrame will fire in the next frame. The browser will work hard to ensure that there are 60 frames per second (60 fps). However, if the browser is unable to it will naturally limit the amount of frames in a second.\n\nFor example, a device might only be able to handle 30 fps and so you will only get 30 frames in that second. Using requestAnimationFrame for throttling is a useful technique in that it prevents you from doing more than 60 updates in a second. If you are doing 100 updates in a second this creates additional work for the browser that the user will not see anyway.\n\n```js\n/**\n * RequestAnimationFrame Throttling\n */\nimport rafSchedule from \"raf-schd\";\nimport React from \"react\";\n\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n\n    this.handleScroll = this.handleScroll.bind(this);\n\n    // Create a new function to schedule updates.\n    this.scheduleUpdate = rafSchedule((point) =\u003e this.props.onScroll(point));\n  }\n\n  handleScroll(e) {\n    // When we receive a scroll event, schedule an update.\n    // If we receive many updates within a frame, we'll only publish the latest value.\n    this.scheduleUpdate({ x: e.clientX, y: e.clientY });\n  }\n\n  componentWillUnmount() {\n    // Cancel any pending updates since we're unmounting.\n    this.scheduleUpdate.cancel();\n  }\n\n  render() {\n    return (\n      \u003cdiv style={{ overflow: \"scroll\" }} onScroll={this.handleScroll}\u003e\n        \u003cimg src=\"/my-huge-image.png\" alt=\"Nature\" /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-requestanimationframe-usiqg9?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain synthetic event in React js?\n\nInside React event handlers, the event object is wrapped in a `SyntheticEvent` object. These objects are pooled, which means that the objects received at an event handler will be reused for other events to increase performance. This also means that accessing the event object\\'s properties asynchronously will be impossible since the event\\'s properties have been reset due to reuse.\n\nThe following piece of code will log null because event has been reused inside the SyntheticEvent pool:\n\n```js\nfunction handleClick(event) {\n  setTimeout(function () {\n    console.log(event.target.name)\n  }, 1000)\n}\n```\n\nTo avoid this we need to store the event\\'s property:\n\n```js\nfunction handleClick(event) {\n  let name = event.target.name\n  setTimeout(function () {\n    console.log(name)\n  }, 1000)\n}\n```\n\n**SyntheticEvent Object:**\n\n```js\nvoid preventDefault()\nvoid stopPropagation()\nboolean isPropagationStopped()\nboolean isDefaultPrevented()\nvoid persist()\nboolean bubbles\nboolean cancelable\nDOMEventTarget currentTarget\nboolean defaultPrevented\nnumber eventPhase\nboolean isTrusted\nDOMEvent nativeEvent\nDOMEventTarget target\nnumber timeStamp\nstring type\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Event Pooling in React?\n\nThe `SyntheticEvent` is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an `asynchronous` way.\n\n**Example:**\n\n```js\nfunction onClick(event) {\n  console.log(event) // =\u003e nullified object.\n  console.log(event.type) // =\u003e \"click\"\n  const eventType = event.type // =\u003e \"click\"\n\n  setTimeout(function() {\n    console.log(event.type) // =\u003e null\n    console.log(eventType) // =\u003e \"click\"\n  }, 0)\n\n  // Won't work. this.state.clickEvent will only contain null values.\n  this.setState({clickEvent: event})\n\n  // You can still export event properties.\n  this.setState({eventType: event.type})\n}\n```\n\nIf we want to access the event properties in an asynchronous way, we should call `event.persist()` on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to trigger click event programmatically?\n\nWe can use `ref` prop to acquire a reference to the underlying `HTMLInputElement` object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the `HTMLElement.click` method.\n\n**Example:**\n\n```js\nclass MyComponent extends React.Component {\n\n  render() {\n    return (\n      \u003cdiv onClick={this.handleClick}\u003e\n        \u003cinput ref={input =\u003e this.inputElement = input} /\u003e\n      \u003c/div\u003e\n    )\n  }\n\n  handleClick = (e) =\u003e {\n    this.inputElement.click()\n  }\n}\n```\n\n*Note: The `ES6 arrow function` provides the correct lexical scope for `this` in the callback.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to listen for click events that are outside of a component?\n\n**Example:**\n\n```js\nclass OutsideAlerter extends Component {\n  // ...\n  componentDidMount() {\n    document.addEventListener(\"mousedown\", this.handleClickOutside);\n  }\n\n  componentWillUnmount() {\n    document.removeEventListener(\"mousedown\", this.handleClickOutside);\n  }\n\n  /**\n   * Set the wrapper ref\n   */\n  setWrapperRef(node) {\n    this.wrapperRef = node;\n  }\n\n  /**\n   * Alert if clicked on outside of element\n   */\n  handleClickOutside(event) {\n    if (this.wrapperRef \u0026\u0026 !this.wrapperRef.contains(event.target)) {\n      alert(\"You clicked outside of me!\");\n    }\n  }\n\n  render() {\n    return \u003cdiv ref={this.setWrapperRef}\u003e{this.props.children}\u003c/div\u003e;\n  }\n}\n\nOutsideAlerter.propTypes = {\n  children: PropTypes.element.isRequired\n};\n\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-click-event-jdf3f?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to convert text to uppercase on user input entered?\n\n```js\nimport React from \"react\";\n\nconst toInputUppercase = (e) =\u003e {\n  e.target.value = (\"\" + e.target.value).toUpperCase();\n};\n\nexport default function App() {\n  const [name, setName] = React.useState(\"\");\n\n  return (\n    \u003cinput\n      name={name}\n      onChange={(e) =\u003e setName(e.target.value)}\n      onInput={toInputUppercase} // apply on input which do you want to be capitalize\n    /\u003e\n  );\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set a dynamic key for state?\n\n**1. Dynamic Key:**\n\n```js\nonChange(e) {\n  const key = e.target.name\n  const value = e.target.value\n  this.setState({ [key]: value })\n}\n```\n\n**2. Nested States:**\n\n```js\nhandleSetState(cat, key, val) {\n  const category = {...this.state[cat]}\n  category[key] = val\n  this.setState({ [cat]: category })\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the pointer events in React?\n\nPointer events, in essence, are very similar to mouse events (mousedown, mouseup, etc.) but are hardware-agnostic and thus can handle all input devices such as a mouse, stylus or touch. This is great since it removes the need for separate implementations for each device and makes authoring for cross-device pointers easier.\n\nThe API of pointer events works in the same manner as existing various event handlers. Pointer events are added as attributes to React component and are passed a callback that accepts an event. Inside the callback we process the event.\n\nThe following event types are now available in React DOM\n\n* onPointerDown\n* onPointerMove\n* onPointerUp\n* onPointerCancel\n* onGotPointerCapture\n* onLostPointerCapture\n* onPointerEnter\n* onPointerLeave\n* onPointerOver\n* onPointerOut\n\n**Example:** Drag and Drop using Point Events\n\n```js\n// App Component\nimport React, { Component } from 'react'\nimport logo from './logo.svg'\nimport './App.css'\nimport DragItem from './DragItem'\n\nclass App extends Component {\n   render() {\n      return (\n        \u003cdiv className=\"App\"\u003e\n          \u003cheader className=\"App-header\"\u003e\n            \u003cimg src={logo} className=\"App-logo\" alt=\"logo\" /\u003e\n            \u003ch1 className=\"App-title\"\u003eWelcome to React sample of Point Events\u003c/h1\u003e\n          \u003c/header\u003e\n          \u003cdiv className=\"App-intro\"\u003e\n            \u003cDragItem /\u003e\n          \u003c/div\u003e\n        \u003c/div\u003e\n      )\n   }\n}\nexport default App\n```\n\nDragItem Component\n\n```js\nimport React from 'react'\nconst CIRCLE_DIAMETER = 100\n\nexport default class DragItem extends React.Component {\n\n  state = {\n     gotCapture: false,\n     circleLeft: 500,\n     circleTop: 100\n  }\n  isDragging = false\n  previousLeft = 0\n  previousTop = 0\n\n  onDown = e =\u003e {\n     this.isDragging = true\n     e.target.setPointerCapture(e.pointerId)\n     this.getDelta(e)\n  }\n  onMove = e =\u003e {\n      if (!this.isDragging) {\n         return\n      }\n  \n      const {left, top} = this.getDelta(e)\n      this.setState(({circleLeft, circleTop}) =\u003e ({\n         circleLeft: circleLeft + left,\n         circleTop: circleTop + top\n      }))\n  }\n  onUp = e =\u003e (this.isDragging = false)\n  onGotCapture = e =\u003e this.setState({gotCapture: true})\n  onLostCapture = e =\u003e this.setState({gotCapture: false})\n  getDelta = e =\u003e {\n      const left = e.pageX\n      const top = e.pageY\n      const delta = {\n         left: left - this.previousLeft,\n         top: top - this.previousTop,\n      }\n      this.previousLeft = left\n      this.previousTop = top\n\n      return delta\n  }\n  render() {\n      const {gotCapture, circleLeft, circleTop} = this.state\n      const boxStyle = {\n         border: '2px solid #cccccc',\n         margin: '10px 0 20px',\n         minHeight: 400,\n         width: '100%',\n         position: 'relative',\n      }\n      const circleStyle = {\n         width: CIRCLE_DIAMETER,\n         height: CIRCLE_DIAMETER,\n         borderRadius: CIRCLE_DIAMETER / 2,\n         position: 'absolute',\n         left: circleLeft,\n         top: circleTop,\n         backgroundColor: gotCapture ? 'red' : 'green',\n         touchAction: 'none',\n      }\n      return (\n         \u003cdiv style={boxStyle}\u003e\n            \u003cdiv\n               style={circleStyle}\n               onPointerDown={this.onDown}\n               onPointerMove={this.onMove}\n               onPointerUp={this.onUp}\n               onPointerCancel={this.onUp}\n               onGotPointerCapture={this.onGotCapture}\n               onLostPointerCapture={this.onLostCapture}\n            /\u003e\n         \u003c/div\u003e\n      )\n  }\n}\n```\n\n*Note: It work only in browsers that support the Pointer Events specification*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is an alternative way to avoid having to bind to this in event callback methods?\n\n**1. Bind in Constructor:**\n\n```js\nclass App extends Component {\n\n  constructor(props) {\n    super(props)\n    this.handleClick = this.handleClick.bind(this)\n  }\n  handleClick() {\n    console.log('Clicked !')\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n**2. Bind in Render:**\n\n```js\nclass App extends Component {\n\n  handleClick() {\n    console.log('Clicked !')\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick.bind(this)}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\n**3. Arrow Function in Render:**\n\n```js\nclass App extends Component {\n\n  handleClick() {\n    console.log('Clicked !')\n  }\n  render() {\n    return \u003cbutton onClick={() =\u003e this.handleClick()}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\n\nUsing an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the alternative of binding `this` in the constructor?\n\n**Arrow Function**: This creates and binds the function all at once. Inside render (and elsewhere), the function is already bound because the arrow function preserves the this binding.\n\n**Example:**\n\n```js\nclass Button extends React.Component {\n  // no binding\n  handleClick = (e) =\u003e {\n    console.log('clicked !');\n  }\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e;\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 8. REACT LISTS\n\n\u003cbr/\u003e\n\n## Q. Explain the Lists in React?\n\nUsing JSX we can show lists using JavaScript\\'s built-in `Array.map()` method. The `.map()` method is often used to take one piece of data and convert it to another.\n\nKeys are unique identifiers that must be attached to the top-level element inside a map. Keys are used by React to know how to update a list whether adding, updating, or deleting items. This is part of how React is so fast with large lists.\n\n**Example:**\n\n```js\n/**\n * React List\n */\nexport default class App extends Component {\n  state = {\n    lists: [\n      { id: 0, context: \"Success\" },\n      { id: 1, context: \"Warning\" },\n      { id: 2, context: \"Danger\" }\n    ]\n  };\n\n  render() {\n    return (\n      \u003c\u003e\n        \u003ch2\u003eReact List\u003c/h2\u003e\n        \u003cul className=\"list-group\"\u003e\n          {this.state.lists.map((list) =\u003e (\n            \u003cli key={list.id}\u003e{list.context}\u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-list-h3wvmz?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why do I need Keys in React Lists?\n\nKeys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:\n\n**Example:**\n\n```js\nconst numbers = [10, 20, 30, 40, 50];\n\nconst listItems = numbers.map((number) =\u003e\n  \u003cli key={number.toString()}\u003e\n    {number}\n  \u003c/li\u003e\n);\n```\n\nReact recommends that you do not use indexes as keys, if the order of items may change. It could impact performance negatively and could lead to some unstable component behaviour.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to display an array of strings in react component?\n\n```js\nconst data = [\"this is line #1\", \"this is line #2\", \"this is line #3\"];\n\nexport default function App() {\n  return (\n    \u003cdiv\u003e\n      {data.map((item, index) =\u003e (\n        \u003cdiv key={index}\u003e{item}\u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-array-of-strings-zz45l?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you render Array, Strings and Numbers in React?\n\n```js\n/**\n * Array Component\n */\nconst items = [\n  { name: \"AngularJS\", description: \"\" },\n  { name: \"React\", description: \"\" },\n  { name: \"Vue.js\", description: \"\" }\n];\nconst ArrayList = (props) =\u003e (\n  \u003cdiv\u003e\n    \u003ch2\u003eRender Array List\u003c/h2\u003e\n    {items.map((item, index) =\u003e (\n      \u003cdiv key={index}\u003e{item.name}\u003c/div\u003e\n    ))}\n  \u003c/div\u003e\n);\n\n\n/**\n * String Component\n */\nconst StringList = (props) =\u003e (\n  \u003cdiv\u003e\n    \u003ch2\u003eRender String List\u003c/h2\u003e\n    {[\"test\", \"render\", \"array\", \"list\"]}\n  \u003c/div\u003e\n);\n\n\n/**\n * Number Component\n */\nconst numbers = [10, 20, 30];\nconst NumberList = (props) =\u003e (\n  \u003cdiv\u003e\n    \u003ch2\u003eRender Number List\u003c/h2\u003e\n    {numbers.map((item, index) =\u003e (\n      \u003cdiv key={index}\u003e{item}\u003c/div\u003e\n    ))}\n  \u003c/div\u003e\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-array-list-uxl6n?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 9. React RESTful API\n\n\u003cbr/\u003e\n\n## Q. How to make a API calls in React?\n\nConsuming REST APIs in a React Application can be done in various ways. Some popular are Axios, fetch etc.\n\n**Example:**\n\n```js\n/**\n * API call using fetch()\n */\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      users: []\n    };\n  }\n\n  componentDidMount() {\n    fetch(\"https://api.github.com/users\")\n      .then((res) =\u003e res.json())\n      .then((result) =\u003e {\n        this.setState({ users: result });\n      });\n  }\n\n  render() {\n    const { users } = this.state;\n    return (\n      \u003cul\u003e\n        {users.map((user) =\u003e (\n          \u003cli key={user.id}\u003e\n            \u003cimg src={user.avatar_url} alt={user.login} width=\"100px\" /\u003e\n          \u003c/li\u003e\n        ))}\n      \u003c/ul\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-api-call-llvlbj?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to display API data using Axios in React?\n\nAxios is a promise based HTTP client for making HTTP requests from a browser to any web server.\n\n**Example:**\n\n```js\n/**\n * GET Request using Axios\n */\nimport React, { useEffect, useState } from \"react\";\nimport axios from \"axios\";\n\nexport default function App() {\n  const [users, setUsers] = useState([]);\n\n  const fetchData = () =\u003e {\n    axios.get(\"https://jsonplaceholder.typicode.com/users\").then((response) =\u003e {\n      setUsers(response.data);\n    });\n  };\n\n  useEffect(() =\u003e {\n    fetchData();\n  }, []);\n\n  return (\n    \u003cdiv\u003e\n      {users.length \u003e 0 \u0026\u0026 (\n        \u003cul\u003e\n          {users.map((user) =\u003e (\n            \u003cli key={user.id}\u003e{user.name}\u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      )}\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-axios-7bhnjt?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make a post call using Axios in React?\n\n**Example:**\n\n```js\n/**\n * POST Request using Axios\n */\n\nimport React from \"react\";\nimport axios from \"axios\";\n\nexport default class PersonList extends React.Component {\n  state = {\n    name: \"\",\n    result: []\n  };\n\n  handleChange = (event) =\u003e {\n    this.setState({ name: event.target.value });\n  };\n\n  handleSubmit = (event) =\u003e {\n    event.preventDefault();\n\n    const user = {\n      name: this.state.name\n    };\n\n    axios\n      .post(`https://jsonplaceholder.typicode.com/users`, { user })\n      .then((res) =\u003e {\n        this.setState({ result: res.data.user.name });\n      });\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cform onSubmit={this.handleSubmit}\u003e\n          \u003clabel\u003e\n            Person Name:\n            \u003cinput type=\"text\" name=\"name\" onChange={this.handleChange} /\u003e\n          \u003c/label\u003e\n          \u003cbutton type=\"submit\"\u003eAdd\u003c/button\u003e\n        \u003c/form\u003e\n        \u003ch4\u003eResult: {this.state.result}\u003c/h4\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-post-request-qp77q5?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the benefits of using Axios() over Fetch() for making http requests?\n\n**1. Fetch()**:\n\nThe Fetch API provides a `fetch()` method defined on the window object. It also provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline (requests and responses). The fetch method has one mandatory argument- the URL of the resource to be fetched. This method returns a Promise that can be used to retrieve the response of the request.\n\n**Example:**\n\n```js\nfetch('path-to-the-resource-to-be-fetched')\n  .then((response) =\u003e {\n    // Code for handling the response\n  })\n  .catch((error) =\u003e {\n    // Error Handling\n  });\n```\n\n**2. Axios()**:\n\nAxios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used intercept HTTP requests and responses and enables client-side protection against XSRF. It also has the ability to cancel requests.\n\n**Example:**\n\n```js\naxios.get('url')\n  .then((response) =\u003e {\n    // Code for handling the response\n  })\n  .catch((error) =\u003e {\n    // Error Handling\n  });\n```\n\n**Differences:**\n\n| Axios()                         | Fetch()                            |\n|---------------------------------|------------------------------------|\n|Axios has **url** in request object. | Fetch has no url in request object.|\n|Axios is a stand-alone third party package that can be easily installed.|Fetch is built into most modern browsers|\n|Axios has built-in XSRF protection.|Fetch does not.|\n|Axios uses the **data** property.  |Fetch uses the **body** property.|\n|Axios data contains the object.    |Fetch\\'s body has to be stringified.|\n|Axios request is ok when status is 200 and statusText is 'OK'.|Fetch request is ok when response object contains the ok property.|\n|Axios performs automatic transforms of JSON data.|Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the `.json()` method on the response.|\n|Axios allows cancelling request and request timeout.|Fetch does not.|\n|Axios has the ability to intercept HTTP requests.|Fetch, by default, doesn\\'t provide a way to intercept requests.|\n|Axios has built-in support for download progress.|Fetch does not support upload progress.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does Axios Interceptors work in React?\n\nAxios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.\n\nInterceptors are methods which are triggered before or after the main method. There are two types of interceptors:\n\n**1. Request Interceptor:**\n\nIt allows you to write or execute a piece of your code before the request gets sent. For example, an authentication token could be injected into all requests.\n\n**Example:**\n\n```js\n// Request Handler\nconst requestHandler = (request) =\u003e {\n  const token = localStorageService.getAccessToken()\n  if (token) {\n    request.headers['Authorization'] = 'Bearer ' + token\n  }\n  return request\n}\n\n// Request Interceptor\naxios.interceptors.request.use(\n  request =\u003e requestHandler(request)\n)\n```\n\n**2. Response Interceptor:**\n\nIt allows you to write or execute a piece of your code before response reaches the calling end.\n\n**Example:**\n\n```js\n// Response Handlers\nconst errorHandler = (error) =\u003e {\n  if (isHandlerEnabled(error.config)) {\n    // Handle errors\n  }\n  return Promise.reject({ ...error })\n}\n\nconst successHandler = (response) =\u003e {\n  if (isHandlerEnabled(response.config)) {\n    // Handle responses\n  }\n  return response\n}\n\n// Response Interceptors\naxios.interceptors.response.use(\n  response =\u003e successHandler(response),\n  error =\u003e errorHandler(error)\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to do caching in React?\n\nIn React, caching data can be achieved in multiple ways\n\n* Local Storage\n* Redux Store\n* Keep data between mouting and unmounting\n* useMemo()\n\n**1. Memoizing Fetched Data:**\n\nMemoization is a technique we would use to make sure that we don\\'t hit the API if we have made some kind of request to fetch it at some initial phase. Storing the result of expensive fetch calls will save the users some load time, therefore, increasing overall performance.\n\n**Example:**\n\n```js\nconst cache = {}\n\nconst useFetch = (url) =\u003e {\n  const [status, setStatus] = useState('idle')\n  const [data, setData] = useState([])\n\n  useEffect(() =\u003e {\n    if (!url) return\n\n    const fetchData = async () =\u003e {\n      setStatus('fetching')\n\n      if (cache[url]) {\n        const data = cache[url]\n        setData(data)\n        setStatus('fetched')\n      } else {\n        const response = await fetch(url)\n        const data = await response.json()\n        cache[url] = data // set response in cache\n        setData(data)\n        setStatus('fetched')\n      }\n    }\n\n    fetchData()\n  }, [url])\n\n  return { status, data }\n}\n```\n\nHere, we\\'re mapping URLs to their data. So, if we make a request to fetch some existing data, we set the data from our local cache, else, we go ahead to make the request and set the result in the cache. This ensures we do not make an API call when we have the data available to us locally.\n\n**2. Memoizing Data With useRef():**\n\nWith `useRef()`, we can set and retrieve mutable values at ease and its value persists throughout the component\\'s lifecycle.\n\n```js\nconst useFetch = (url) =\u003e {\n  const cache = useRef({})\n  const [status, setStatus] = useState('idle')\n  const [data, setData] = useState([])\n\n  useEffect(() =\u003e {\n    if (!url) return\n\n    const fetchData = async () =\u003e {\n      setStatus('fetching')\n\n      if (cache.current[url]) {\n        const data = cache.current[url]\n        setData(data)\n        setStatus('fetched')\n      } else {\n        const response = await fetch(url)\n        const data = await response.json()\n        cache.current[url] = data // set response in cache\n        setData(data)\n        setStatus('fetched')\n      }\n    }\n\n    fetchData()\n  }, [url])\n\n  return { status, data }\n}\n```\n\n**3. Using localStorage():**\n\n```js\nconst InitialState = {\n   someState: 'a'\n}\nclass App extends Component {\n\n constructor(props) {\n  super(props)\n\n  // Retrieve the last state\n  this.state = localStorage.getItem(\"appState\") ? JSON.parse(localStorage.getItem(\"appState\")) : InitialState\n\n}\n\ncomponentWillUnmount() {\n  // Remember state for the next mount\n  localStorage.setItem('appState', JSON.stringify(this.state))\n}\n\nrender() {\n  ...\n }\n}\n\nexport default App\n```\n\n**4. Keep data between Mouting and Unmounting:**\n\n```js\nimport React, { Component } from 'react'\n\n// Set initial state\nlet state = { counter: 5 }\n\nclass Counter extends Component {\n\n constructor(props) {\n  super(props)\n\n  // Retrieve the last state\n  this.state = state\n\n  this.onClick = this.onClick.bind(this)\n}\n\ncomponentWillUnmount() {\n  // Remember state for the next mount\n  state = this.state\n}\n\nonClick(e) {\n  e.preventDefault()\n  this.setState(prev =\u003e ({ counter: prev.counter + 1 }))\n}\n\nrender() {\n  return (\n    \u003cdiv\u003e\n      \u003cspan\u003e{ this.state.counter }\u003c/span\u003e\n      \u003cbutton onClick={this.onClick}\u003eIncrease\u003c/button\u003e\n    \u003c/div\u003e\n  )\n }\n}\n\nexport default Counter\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. In which lifecycle event do you make AJAX requests in React?\n\nAccording to official React docs, the recommended place to do Ajax requests is in **componentDidMount()** which is a lifecycle method that runs after the React component has been mounted to the DOM. This is so you can use `setState()` to update your component when the data is retrieved.\n\n**Example:**\n\n```js\n/**\n * API call in componentDidMount()\n */\nimport React from \"react\";\n\nexport default class App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      error: null,\n      isLoaded: false,\n      users: []\n    };\n  }\n\n  componentDidMount() {\n    fetch(\"https://dummy.restapiexample.com/api/v1/employees\")\n      .then((res) =\u003e res.json())\n      .then((result) =\u003e {\n        this.setState({\n          isLoaded: true,\n          users: result.data\n        });\n      })\n      .catch((error) =\u003e {\n        this.setState({\n          isLoaded: false,\n          error\n        });\n      });\n  }\n\n  render() {\n    const { error, isLoaded, users } = this.state;\n\n    if (error) {\n      return \u003cdiv\u003eError: {error.message}\u003c/div\u003e;\n    } else if (!isLoaded) {\n      return \u003cdiv\u003eLoading...\u003c/div\u003e;\n    } else {\n      return (\n        \u003cul\u003e\n          {users.length \u003e 0 \u0026\u0026\n            users.map((user) =\u003e \u003cli key={user.id}\u003e{user.employee_name}\u003c/li\u003e)}\n        \u003c/ul\u003e\n      );\n    }\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-componentdidmount-96ys6r?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use async await in React?\n\n**Example:**\n\n```js\n\nclass App extends Component {\n  // ...\n  async componentDidMount() {\n    try {\n      const response = await fetch(`https://api.github.com/users`);\n\n      if (!response.ok) {\n        throw Error(response.statusText);\n      } else {\n        const json = await response.json();\n        this.setState({ data: json });\n      }\n    } catch (error) {\n      console.log(error);\n    }\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cul\u003e\n          {this.state.data.map((el) =\u003e (\n            \u003cli key={el.id}\u003e\n              \u003cimg src={el.avatar_url} alt={el.avatar_url} /\u003e\n              \u003cspan className=\"UserLogin\"\u003e{el.login}\u003c/span\u003e\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-async-await-7mu7t?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How RxJS is used in React for state management?\n\nRxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. Reactive programming is an event-based paradigm that allows us to run asynchronous sequences of events as soon as data is pushed to a consumer.\n\n**RxJS Terminology:**\n\n* **Observable**: An Observable is a data stream that houses data that can be passed through different threads.\n* **Observer**: An Observer consumes the data supplied by an Observable\n* **Subscription**: In order for Observer to consume data from Observable, Observer has to subscribe it to the Observable.\n* **Subject**: An RxJS Subject can act as both an Observable and an Observer at the same time. In this way, values can be multicasted to many Observers from it so that when a Subject receives any data, that data can be forwarded to every Observer subscribed to it.\n* **Operators**: Operators are methods that can use on Observables and subjects to manipulate, filter or change the Observable in a specified manner into a new Observable.\n* **BehaviorSubject**: It allows multiple observers to listen on stream and events multicasted to the observers, BehaviorSubject stores the latest value and broadcasts it to any new subscribers.\n\n**Example:**\n\n```js\n// messageService.js\nimport { BehaviourSubject } from 'rxjs'\n\nconst subscriber = new BehaviourSubject(0)\n\nconst messageService = {\n   send: function(msg) {\n     subscriber.next(msg)\n   }\n}\nexport {\n  messageService,\n  subscriber\n}\n```\n\nThe messageService object has a send function, which takes a msg parameter which holds the data we need to broadcast all listening components, in the function body we call the emit method in the subscriber object it multicasts the data to the subscribing components.\n\n```js\nimport React, { Component } from 'react'\nimport { render } from 'react-dom'\nimport './style.css'\nimport { subscriber, messageService } from './messageService'\n\nclass ConsumerA extends React.Component {\n  constructor() {\n    this.state = {\n      counter: 0\n    }\n  }\n\n  componentDidMount() {\n    subscriber.subscribe((v) =\u003e {\n      let { counter } = this.state\n      counter = counter + v\n      this.setState({ counter })\n    })\n  }\n\n  render() {\n    let { counter } = this.state\n    return (\n      \u003cdiv\u003e\n        \u003chr/\u003e\n          \u003ch3\u003e Counter for Consumer A \u003c/h3\u003e\n          \u003cdiv\u003e Counter: {counter} \u003c/div\u003e\n        \u003chr/\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nclass ConsumerB extends React.Component {\n  constructor() {\n    this.state = {\n      counter: 0\n    }\n  }\n  componentDidMount() {\n    subscriber.subscribe((v) =\u003e {\n      let { counter } = this.state\n      counter = counter + v\n      this.setState({ counter })\n    })\n  }\n\n  render() {\n    let { counter } = this.state\n    return (\n      \u003cdiv\u003e\n        \u003chr/\u003e\n          \u003ch3\u003eCounter for Consumer B\u003c/h3\u003e\n          \u003cdiv\u003e Counter: { counter } \u003c/div\u003e\n        \u003chr/\u003e\n        \u003cProducerB /\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nclass ProducerA extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch3\u003eProducerA\u003c/h3\u003e\n        \u003cbutto onClick={(e) =\u003e subscriber.next(1)}\u003eIncrement Counter\u003c/button\u003e\n        \u003cConsumerA /\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nclass ProducerB extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch3\u003eProducerB\u003c/h3\u003e\n        \u003cbutton onClick={(e) =\u003e subscriber.next(-1)}\u003eDecrement Counter\u003c/button\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nclass App extends Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cProducerA /\u003e\n        \u003chr/\u003e\n        \u003cConsumerB /\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nrender(\u003cApp/\u003e, document.getElementById('root'));\n```\n\nThe ConsumerA and ConsumerB components keep a state counter individual. In their componentDidMount they subscribe to the same stream subscriber, anytime an event is published they both update the counter. The ProducerA and ProducerB have buttons Increment Counter and Decrement Counter when clicked they emit `1` or `-1`.\n\n**Reference:**\n\n* *[https://www.learnrxjs.io/](https://www.learnrxjs.io/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 10. REACT FORMS\n\n\u003cbr/\u003e\n\n## Q. How dynamically generate menu options for `\u003cselect\u003e` from an array?\n\n**Example:**\n\n```js\nclass App extends React.Component {\n\n  constructor(props) {\n    super(props);\n    this.state = {\n      colors: {}\n    };\n    this.selectColor = this.selectColor.bind(this);\n  }\n\n  selectColor = (e) =\u003e {\n    console.log(\"Selected Color: \", e.target.value);\n  };\n\n  componentDidMount() {\n    this.setState({\n      colors: {\n        \"#ff0000\": \"Red\",\n        \"#00ff00\": \"Green\",\n        \"#0000ff\": \"Blue\"\n      }\n    });\n  }\n\n  render() {\n    const { colors } = this.state;\n\n    let colorsList = Object.keys(colors).map((k) =\u003e {\n      return (\n        \u003coption key={k} value={k}\u003e\n          {colors[k]}\n        \u003c/option\u003e\n      );\n    }, this);\n\n    return (\n      \u003cdiv\u003e\n        \u003cselect onChange={this.selectColor}\u003e{colorsList}\u003c/select\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-select-dropdown-1oz9f?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How would you create a form in React?\n\n**Example:**\n\n```js\nimport React from \"react\";\nimport \"./styles.css\";\n\nconst countries = [\"Austria\", \"India\", \"Italy\", \"Russia\", \"United States\"];\n\nexport default function App() {\n  const [email, setEmail] = React.useState(\"\");\n  const [password, setPassword] = React.useState(\"\");\n  const [country, setCountry] = React.useState(\"\");\n  const [acceptedTerms, setAcceptedTerms] = React.useState(false);\n\n  const handleSubmit = (event) =\u003e {\n    console.log(`\n      Email: ${email}\n      Password: ${password}\n      Country: ${country}\n      Accepted Terms: ${acceptedTerms}\n    `);\n    event.preventDefault();\n  };\n\n  return (\n    \u003cform onSubmit={handleSubmit}\u003e\n      \u003ch1\u003eCreate Account\u003c/h1\u003e\n\n      \u003clabel\u003eEmail:\n        \u003cinput name=\"email\" type=\"email\" value={email}\n          onChange={(e) =\u003e setEmail(e.target.value)}\n          required\n        /\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003ePassword:\n        \u003cinput name=\"password\" type=\"password\" value={password}\n          onChange={(e) =\u003e setPassword(e.target.value)}\n          required\n        /\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003eCountry:\n        \u003cselect name=\"country\" value={country}\n          onChange={(e) =\u003e setCountry(e.target.value)}\n          required\n        \u003e\n          \u003coption key=\"\"\u003e\u003c/option\u003e\n          {countries.map((country) =\u003e (\n            \u003coption key={country}\u003e{country}\u003c/option\u003e\n          ))}\n        \u003c/select\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003e\u003cinput name=\"acceptedTerms\" type=\"checkbox\"\n          onChange={(e) =\u003e setAcceptedTerms(e.target.value)}\n          required\n        /\u003e\n        I accept the terms of service\n      \u003c/label\u003e\n\n      \u003cbutton\u003eSubmit\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n**Output:**\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src='assets/react-form.png' alt='React Form' width='500px' /\u003e\n\u003c/p\u003e\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-form-p9z2y)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use react hook form with material-ui?\n\n**Installation:**\n\n```js\nnpm install react-hook-form\nnpm install material-ui\n```\n\n**Example:**\n\n```js\nimport React from \"react\";\nimport { makeStyles } from \"@material-ui/core\";\nimport TextField from \"@material-ui/core/TextField\";\nimport Button from \"@material-ui/core/Button\";\nimport { useForm, Controller } from \"react-hook-form\";\n\nconst useStyles = makeStyles((theme) =\u003e ({\n  root: {\n    display: \"flex\",\n    flexDirection: \"column\",\n    justifyContent: \"center\",\n    alignItems: \"center\",\n    padding: theme.spacing(2),\n\n    \"\u0026 .MuiTextField-root\": {\n      margin: theme.spacing(1),\n      width: \"300px\"\n    },\n    \"\u0026 .MuiButtonBase-root\": {\n      margin: theme.spacing(2)\n    }\n  }\n}));\n\nconst Form = ({ handleClose }) =\u003e {\n  const classes = useStyles();\n  const { handleSubmit, control } = useForm();\n\n  const onSubmit = (data) =\u003e {\n    console.clear();\n    console.log(data);\n  };\n\n  return (\n    \u003cform className={classes.root} onSubmit={handleSubmit(onSubmit)}\u003e\n      \u003cController\n        name=\"email\"\n        control={control}\n        defaultValue=\"\"\n        render={({ field: { onChange, value }, fieldState: { error } }) =\u003e (\n          \u003cTextField\n            label=\"Email\"\n            variant=\"filled\"\n            value={value}\n            onChange={onChange}\n            error={!!error}\n            helperText={error ? error.message : null}\n            type=\"email\"\n          /\u003e\n        )}\n        rules={{ required: \"Email required\" }}\n      /\u003e\n      \u003cController\n        name=\"password\"\n        control={control}\n        defaultValue=\"\"\n        render={({ field: { onChange, value }, fieldState: { error } }) =\u003e (\n          \u003cTextField\n            label=\"Password\"\n            variant=\"filled\"\n            value={value}\n            onChange={onChange}\n            error={!!error}\n            helperText={error ? error.message : null}\n            type=\"password\"\n          /\u003e\n        )}\n        rules={{ required: \"Password required\" }}\n      /\u003e\n      \u003cdiv\u003e\n        \u003cButton variant=\"contained\" onClick={handleClose}\u003e\n          Cancel\n        \u003c/Button\u003e\n        \u003cButton type=\"submit\" variant=\"contained\" color=\"primary\"\u003e\n          Signup\n        \u003c/Button\u003e\n      \u003c/div\u003e\n    \u003c/form\u003e\n  );\n};\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hook-form-dc8m7)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why You Should Choose React Hook Form Over Formik and Redux-Form?\n\nBelow are the main reasons to recommend React Hook Form Over Formik and Redux-Form,\n\n**1. Isolate Component Re-Rendering:**\n\nReact Hook Form isolates the component and avoids the other components from re-rending. This feature will improve the performance by avoiding unwanted rendering in other child components. However, libraries like Formik and Redux-Form re-render the other child components along with the form component.\n\n**2. Reduce Rendering:**\n\nBesides isolating the component, it also limits its own (form components) form re-rendering on particular events such as onChange, onBlur, etc.\n\n**3. Faster Mounting:**\n\nMounting time is about 13% faster than Formik and 25% faster than Redux-Form. In other words, the form\\'s DOM elements will be inserted into the DOM tree quicker, leading to fast rendering compared with other libraries.\n\n**4. Input Change Subscriptions:**\n\nReact Hook Form allows you to subscribe to each input element without going through the re-rendering of each element inside the form component.\n\n**5. Typescript Support:**\n\nReact Hook Form is built with TypeScript and can define a FormData type to support form values.\n\n**6. Less Code to Maintain:**\n\nThe React Hook Form provides a hook called `useForm()`, consisting of methods and props handleSubmit, register, and errors. They would handle the submit events, the input via refs using register, and display any errors. However, in the other two libraries, you need to write your custom handlers for events and validations.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are controlled and uncontrolled components in React?\n\nIn a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.\n\n**1. Controlled Components:**  \n\nIn a controlled component, the form data is handled by the state within the component. The state within the component serves as “the single source of truth” for the input elements that are rendered by the component.\n\n**Example:**\n\n```js\n/**\n * Controlled Components\n */\nimport React, { Component } from \"react\";\n\nexport default class App extends Component {\n  state = {\n    message: \"\"\n  };\n  updateMessage = (newText) =\u003e {\n    console.log(newText);\n    this.setState(() =\u003e ({\n      message: newText\n    }));\n  };\n  render() {\n    return (\n      \u003cdiv className=\"App\"\u003e\n        \u003cdiv className=\"container\"\u003e\n          \u003cinput\n            type=\"text\"\n            placeholder=\"Your message here..\"\n            value={this.state.message}\n            onChange={(event) =\u003e this.updateMessage(event.target.value)}\n          /\u003e\n          \u003ch3\u003eMessage: {this.state.message}\u003c/h3\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-controlled-components-1ilt72?file=/src/App.js)**\n\n**2. Uncontrolled Components:**  \n\nUncontrolled components act more like traditional HTML form elements. The data for each input element is stored in the DOM, not in the component. Instead of writing an event handler for all of your state updates, It uses `ref` to retrieve values from the DOM. `Refs` provide a way to access DOM nodes or React elements created in the render method.\n\n```js\n/**\n * Uncontrolled Component\n */\nimport React, { Component } from \"react\";\n\nexport default class App extends Component {\n  constructor(props) {\n    super(props);\n    this.handleChange = this.handleChange.bind(this);\n    this.input = React.createRef();\n  }\n  handleChange = (newText) =\u003e {\n    console.log(newText);\n  };\n  render() {\n    return (\n      \u003cdiv className=\"App\"\u003e\n        \u003cdiv className=\"container\"\u003e\n          \u003cinput\n            type=\"text\"\n            placeholder=\"Your message here..\"\n            ref={this.input}\n            onChange={(event) =\u003e this.handleChange(event.target.value)}\n          /\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-uncontrolled-component-4o7lw7?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you set default value for uncontrolled components?\n\nReact provides **defaultValue** attribute that pre-populate the input field with the default Value without overriding any value input by the user.\n\n**Example:**\n\n```js\n/**\n * React defaultValue\n */\nrender() {\n  return (\n    \u003cform onSubmit={this.handleSubmit}\u003e\n      \u003clabel\u003e\n        Name:\n        \u003cinput\n          defaultValue=\"Samir Chahal\"\n          type=\"text\"\n          ref={this.input} /\u003e\n      \u003c/label\u003e\n      \u003cinput type=\"submit\" value=\"Submit\" /\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-form-qmx9s?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 11. REACT HOOKS\n\n\u003cbr/\u003e\n\n## Q. What are React Hooks?\n\nReact Hooks are in-built functions that allow to use **state** and **lifecycle** methods inside functional components, they also work together with existing code, so they can easily be adopted into a codebase.\n\n**Rules of Hooks:**\n\n* Hooks should not be called inside loops, conditions, or nested functions.\n* Hooks should be used inside React function components\n\n**Built-in Hooks:**\n\n| Hooks               | Description                                                                     |\n|---------------------|---------------------------------------------------------------------------------|\n|useState()           |To manage states. Returns a stateful value and an updater function to update it. |\n|useEffect()          |To manage side-effects like API calls, subscriptions, timers, mutations, and more.|\n|useContext()         |To return the current value for a context.|\n|useReducer()         |A useState alternative to help with complex state management.|\n|useCallback()        |It returns a memorized version of a callback to help a child component not re-render unnecessarily.|\n|useMemo()            |It returns a memoized value that helps in performance optimizations.|\n|useRef()             |It returns a ref object with a `.current` property. The ref object is mutable. It is mainly used to access a child component imperatively.|\n|useImperativeHandle()|It customizes the instance value that is exposed to parent components when using ref.|\n|useLayoutEffect()    |It fires at the end of all DOM mutations. It\\'s best to use useEffect as much as possible over this one as the useLayoutEffect fires synchronously.|\n|useDebugValue()      |Helps to display a label in React DevTools for custom hooks.\n\n**Example:**\n\n```js\n/**\n * useState() Hooks\n */\nimport React, { useState } from \"react\";\n\nexport default function App() {\n  const [isButtonClicked, setIsButtonClickedStatus] = useState(false);\n\n  return (\n    \u003cbutton onClick={() =\u003e setIsButtonClickedStatus(!isButtonClicked)}\u003e\n      {isButtonClicked ? \"Clicked\" : \"Click Me, Please\"}\n    \u003c/button\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usestate-mqb4jb?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are advantages of using React Hooks?\n\n* Hooks are easier to work with and to test (as separated functions from React components*) and make the code look cleaner, easier to read — a related logic can be tightly coupled in a custom hook.\n* Hooks allow to do by breaking the logic between components into small functions and using them inside the components.\n* Improved code reuse\n* Better code composition\n* Better defaults\n* Sharing non-visual logic with the use of custom hooks\n* Flexibility in moving up and down the components tree.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create custom Hooks?\n\nReact also allows us to create custom Hooks with unique features that extracts component logic into reusable functions.\n\nA custom Hooks has following features:\n\n* As a function, it takes input and returns output.\n* Its name starts with **use** like useQuery, useMedia…\n* Unlike functional components, custom hooks return a normal, non-jsx data.\n* Unlike normal functions, custom hooks can use other hooks such as useState, useRef… and other custom hooks.\n\n**Example:** Custom Hook - useFetch()\n\n```js\n/**\n * Custom Hook\n */\nimport { useState, useEffect } from \"react\";\n\nconst useFetch = (url) =\u003e {\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\nexport default useFetch;\n```\n\n```js\n/**\n * App Component\n */\nimport \"./styles.css\";\nimport useFetch from \"./useFetch\";\n\nexport default function App() {\n  // custom hook\n  const [data] = useFetch(\"https://jsonplaceholder.typicode.com/todos\");\n  return (\n    \u003c\u003e\n      {data \u0026\u0026\n        data.map((item) =\u003e {\n          return \u003cp key={item.id}\u003e{item.title}\u003c/p\u003e;\n        })}\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-custom-hooks-2x8eu9?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to fetch data with React Hooks?\n\nThe **useState()** is a hook used to maintain local states in function components and **useEffect()** hook is used to execute functions after a component gets rendered (to \"perform side effects\").\n\n**Example:**\n\n```js\n/**\n * useState() and useEffect() Hooks\n */\nimport React, { useState, useEffect } from \"react\";\n\nexport default function App() {\n  const [users, setUsers] = useState([]);\n\n  useEffect(() =\u003e {\n    fetch(\"https://api.github.com/users\")\n      .then((response) =\u003e response.json())\n      .then((data) =\u003e {\n        setUsers(data);\n      });\n  }, []);\n\n  return (\n    \u003cdiv\u003e\n      {users.map((user) =\u003e (\n        \u003cdiv key={user.id}\u003e\n          \u003cspan\u003e\n            \u003cimg src={user.avatar_url} width={\"30px\"} alt={user.avatar_url} /\u003e\n          \u003c/span\u003e\n          \u003cspan\u003e {user.login.toUpperCase()}\u003c/span\u003e\n        \u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hooks-siuu6t?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Do Hooks replace render props and higher-order components?\n\n**1. Using React Hooks:**\n\nHooks were designed to replace `class` and provide another great alternative to compose behavior into your components. Higher Order Components are also useful for composing behavior. Hooks encapsulate the functionality to easily reusable functions\n\n```js\nconst [active, setActive] = useState(defaultActive)\n```\n\nThere are few build-in Hooks\n\n```js\nimport {\n  useState,\n  useReducer,\n  useEffect,\n  useCallback,\n  useMemo,\n  useRef,\n  ...\n} from 'react'\n```\n\n**2. Using Higher Order Components:**\n\nA Higher Order Component (HOC) is a component that takes a component and returns a component. HOCs are composable using point-free, declarative function composition.\n\n**Example:** logger API\n\n```js\nimport React, { useEffect } from 'react'\n\nconst withLogging = Component =\u003e props =\u003e {\n  useEffect(() =\u003e {\n    fetch(`/logger?location=${ window.location}`)\n  }, [])\n  return \u003cComponent {...props } /\u003e\n}\nexport default withLogging\n```\n\nTo use it, you can mix it into an HOC that you\\’ll wrap around every page:\n\n```js\nimport React from 'react'\nimport withAuth from './with-auth.js'\nimport withLogging from './with-logging.js'\nimport withLayout from './with-layout.js'\n\nconst page = compose(\n  withRedux,\n  withAuth,\n  withLogging,\n  withLayout('default'),\n)\nexport default page\n```\n\nTo use this for a page\n\n```js\nimport page from '../hocs/page.js'\nimport MyPageComponent from './my-page-component.js'\n\nexport default page(MyPageComponent)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to compare oldValues and newValues on React Hooks useEffect?\n\nWe can store old values in a **ref** since assigning values to them won\\'t trigger a re-rendering of the component but the value will persist after each render cycle.\n\n**Example:**\n\n```js\n// To store old values\nconst usePrevious = (value) =\u003e {\n  const ref = useRef();\n  useEffect(() =\u003e {\n    ref.current = value;\n  });\n  return ref.current;\n};\n\nexport default function App() {\n  const [count, setCount] = useState(0);\n  const prevCount = usePrevious(count);\n\n  useEffect(() =\u003e {\n    console.log(\"prevCount: \", prevCount, \"count: \", count);\n  }, [prevCount, count]);\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={() =\u003e setCount((c) =\u003e c + 10)}\u003eIncrement\u003c/button\u003e\n      \u003cp\u003e{count}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\nHere, We create the **usePrevious** hook with the value parameter which is state we want to get the previous value from,\nIn the hook, we create a ref with the **useRef** hook to create a non-reactive property. Then we add the **useEffect** hook with a callback that sets the **ref.current** to value to set the previous value.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hooks-useeffect-ho6vh?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to re-render the view when the browser is resized?\n\n**1. Using React Hooks:**\n\n```js\nimport React, { useLayoutEffect, useState } from 'react'\n\nfunction useWindowSize() {\n\n  const [size, setSize] = useState([0, 0])\n\n  useLayoutEffect(() =\u003e {\n    function updateSize() {\n      setSize([window.innerWidth, window.innerHeight])\n    }\n    window.addEventListener('resize', updateSize)\n    updateSize()\n    return () =\u003e window.removeEventListener('resize', updateSize)\n  }, [])\n\n  return size\n}\n\nfunction ShowWindowDimensions(props) {\n\n  const [width, height] = useWindowSize()\n  return \u003cspan\u003eWindow size: {width} x {height}\u003c/span\u003e\n}\n```\n\n**2. Using React Class:**\n\n```js\nimport React from 'react'\n\nclass ShowWindowDimensions extends React.Component {\n  \n  state = { width: 0, height: 0 }\n  \n  updateDimensions = () =\u003e {\n    this.setState({ width: window.innerWidth, height: window.innerHeight })\n  }\n  /**\n   * Add event listener\n   */\n  componentDidMount() {\n    window.addEventListener('resize', this.updateDimensions)\n  }\n  /**\n   * Remove event listener\n   */\n  componentWillUnmount() {\n    window.removeEventListener('resize', this.updateDimensions)\n  }\n\n  render() {\n    return (\n      \u003cspan\u003eWindow size: {this.state.width} x {this.state.height}\u003c/span\u003e\n    )\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can I force a component to re-render with hooks in React?\n\nThe **useState()** or **useReducer()** hooks can be used to force a React component to rerender.\n\nThe example below is equivalent to **forceUpdate()** method in class-based components. This hook works in the following way:\n\n* The `useState()` hook returns an array with two elements, a value and an updater function.\n* Here, we are instantly calling the updater function, which in this case is called with `undefined`, so it is the same as calling `updater(undefined)`.\n\n**Example:**\n\n```js\n/**\n * Rerender Component with useState()\n */\nimport React, { useState } from \"react\";\n\nconst useForceUpdate = () =\u003e useState()[1];\n\nexport default function App() {\n  const forceUpdate = useForceUpdate();\n  console.log(\"Rendered\");\n\n  return \u003cbutton onClick={forceUpdate}\u003eUpdate Me\u003c/button\u003e;\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-re-render-with-hooks-9c3ui?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is useState() in React?\n\nThe `useState()` is a Hook that allows to have state variables in functional components.\n\n```js\nimport React, { useState } from 'react'\n\nconst App = () =\u003e {\n  const [count, setCount] = React.useState(0)\n\n  const handleIncrease = () =\u003e {\n    setCount(count + 1)\n  }\n\n  const handleDecrease = () =\u003e {\n    setCount(count - 1)\n  }\n\n  return (\n    \u003cdiv\u003e\n      Count: {count}\n      \u003chr /\u003e\n      \u003cdiv\u003e\n        \u003cbutton type=\"button\" onClick={handleIncrease}\u003e\n          Increase\n        \u003c/button\u003e\n        \u003cbutton type=\"button\" onClick={handleDecrease}\u003e\n          Decrease\n        \u003c/button\u003e\n      \u003c/div\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\nThe useState() function takes as argument a value for the initial state. In this case, the count starts out with 0. In addition, the hook returns an array of two values: **count** and **setCount**. It\\'s up to you to name the two values, because they are `destructured from the returned array` where renaming is allowed.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why do we use array destructuring in useState?\n\nThe `useState` hook allows us to make our function components stateful. When called, `useState()` returns an array of two items. The first being our state value and the second being a function for setting or updating that value. The `useState` hook takes a single argument, the initial value for the associated piece of state, which can be of any Javascript data type.\n\n```js\nimport React, { useState } from 'react';\n\nconst Component = () =\u003e {\n    const [value, setValue] = useState(initial value)\n    ...\n```\n\n**Example:** State with Various Data Types\n\n```js\nconst [count, setCount] = useState(0)\nconst [color, setColor] = useState('#526b2d')\nconst [isHidden, setIsHidden] = useState(true)\nconst [products, setProducts] = useState([])\nconst [user, setUser] = useState({\n    username: '',\n    avatar: '',\n    email: '',\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is useReducer() in React?\n\nIt accepts a reducer function with the application initial state, returns the current application state, then dispatches a function.\n\nAlthough `useState()` is a Basic Hook and `useReducer()` is an Additional Hook, `useState()` is actually implemented with `useReducer()`. This means `useReducer()` is primitive and we can use `useReducer()` for everything can do with useState(). Reducer is so powerful that it can apply for various use cases.\n\n**Example:**\n\n```js\nimport React, { useReducer } from 'react'\n\nconst initialState = 0\nconst reducer = (state, action) =\u003e {\n  switch (action) {\n    case 'increment': return state + 1\n    case 'decrement': return state - 1\n    case 'reset': return 0\n    default: throw new Error('Unexpected action')\n  }\n}\n\nconst ReducerExample = () =\u003e {\n  const [count, dispatch] = useReducer(reducer, initialState)\n  return (\n    \u003cdiv\u003e\n      {count}\n      \u003cbutton onClick={() =\u003e dispatch('increment')}\u003e+1\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch('decrement')}\u003e-1\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch('reset')}\u003ereset\u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default ReducerExample\n```\n\nHere, we first define an initialState and a reducer. When a user clicks a button, it will dispatch an action which updates the count and the updated count will be displayed. We could define as many actions as possible in the reducer, but the limitation of this pattern is that actions are finite.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does React renderer work exactly when we call setState?\n\nThe `state` allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule. Components defined as classes have some additional features. Local state is a feature available only to class Components.\n\nThe `setState()` is the API method provided with the library so that the user is able to define and manipulate state over time.\n`setState()` is the only legitimate way to update state after the initial state setup.\n\n**Example:**\n\n```js\nimport React, { Component } from 'react'\n\nclass Search extends Component {\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      searchString: ''\n    }\n  }\n}\n```\n\nwe are passing an empty string as a value and, to update the state of searchString, we have to call setState().\n\n```js\nsetState({ searchString: event.target.value })\n```\n\nHere, we are passing an object to setState(). The object contains the part of the state we want to update which, in this case, is the value of searchString. This is basically kicking off a process that React calls **reconciliation**. The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state.\n\nWhen the request to `setState()` is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the Search component\\'s UI should change in response to the state change by comparing it with the elements of the previous tree.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a Webhook in React?\n\nWeb hooks provide a mechanism where by a server-side application can notify a client-side application when a new event (that the client-side application might be interested in) has occurred on the server.\n\nWebhooks are also sometimes referred to as \"Reverse APIs\". In APIs, the client-side application calls (consumes) the server-side application. Whereas, in case of web hooks it is the server-side that calls (consumes) the web hook (the end-point URL provided by the client-side application), i.e. it is the server-side application that calls the client-side application.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Exlain is useCallback(), useMemo(), useImperativeHandle(), useLayoutEffect(), useDebugValue() in React?\n\n**1. useCallback():**\n\nReact\\'s `useCallback()` Hook can be used to optimize the rendering behavior of your React function components. The `useCallback` will return a memoized version of the callback that only changes if one of the dependencies has changed.\n\nThis is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).\n\n**Example:**\n\n```js\n/**\n * useCallback()\n */\nimport React, { useState, useCallback, useEffect } from \"react\";\n\nconst count = new Set();\n\nexport default function App() {\n  const [counter, setCounter] = useState(0);\n\n  const increment = useCallback(() =\u003e {\n    setCounter(counter + 1);\n  }, [counter]);\n\n  useEffect(() =\u003e {\n    count.add(increment);\n    console.log(count.size);\n  }, [increment]);\n\n  return (\n    \u003c\u003e\n      \u003ch1\u003euseCallback()\u003c/h1\u003e\n      \u003ch2\u003eFunction Call: {count.size}\u003c/h2\u003e\n      \u003cbutton onClick={increment}\u003eIncrement\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usecallback-zecshz?file=/src/App.js)**\n\n**2. useMemo():**\n\nThe `useMemo()` is similar to `useCallback()` except it allows you to apply memoization to any value type. It does this by accepting a function which returns the value and then that function is only called when the value needs to be retrieved.\n\n**Example:**\n\nReact application which renders a list of users and allows us to filter the users by their name. The filter happens only when a user explicitly clicks a button; not already when the user types into the input field.\n\n```js\nimport React from 'react'\n\nconst users = [\n  { id: 'a', name: 'Robin' },\n  { id: 'b', name: 'Dennis' },\n]\n\nconst App = () =\u003e {\n  const [text, setText] = React.useState('')\n  const [search, setSearch] = React.useState('')\n\n  const handleText = (event) =\u003e {\n    setText(event.target.value)\n  }\n\n  const handleSearch = () =\u003e {\n    setSearch(text)\n  }\n\n  // useMemo Hooks\n  const filteredUsers = React.useMemo(\n    () =\u003e\n      users.filter((user) =\u003e {\n        console.log('Filter function is running ...');\n        return user.name.toLowerCase().includes(search.toLowerCase());\n      }),\n    [search]\n  );\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput type=\"text\" value={text} onChange={handleText} /\u003e\n      \u003cbutton type=\"button\" onClick={handleSearch}\u003e\n        Search\n      \u003c/button\u003e\n\n      \u003cList list={filteredUsers} /\u003e\n    \u003c/div\u003e\n  )\n}\n\nconst List = ({ list }) =\u003e {\n  return (\n    \u003cul\u003e\n      {list.map((item) =\u003e (\n        \u003cListItem key={item.id} item={item} /\u003e\n      ))}\n    \u003c/ul\u003e\n  )\n}\n\nconst ListItem = ({ item }) =\u003e {\n  return \u003cli\u003e{item.name}\u003c/li\u003e\n}\n\nexport default App\n```\n\nHere, the **filteredUsers** function is only executed once the search state changes. It doesn\\'t run if the text state changes, because that\\'s not a dependency for this filter function and thus not a dependency in the dependency array for the useMemo hook.\n\n**3. useImperativeHandle():**\n\n`useImperativeHandle()` customizes the instance value that is exposed to parent components when using `ref`. As always, imperative code using `refs` should be avoided in most cases. `useImperativeHandle` should be used with `forwardRef`.\n\n```js\nfunction FancyInput(props, ref) {\n  const inputRef = useRef()\n  useImperativeHandle(ref, () =\u003e ({\n    focus: () =\u003e {\n      inputRef.current.focus()\n    }\n  }))\n  return \u003cinput ref={inputRef} ... /\u003e\n}\nFancyInput = forwardRef(FancyInput)\n```\n\n**4. useLayoutEffect():**\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/useLayoutEffect.png\" alt=\"useLayoutEffect\" width=\"600px\" /\u003e\n\u003c/p\u003e\n\nThis runs synchronously immediately after React has performed all DOM mutations. This can be useful if you need to make DOM measurements (like getting the scroll position or other styles for an element) and then make DOM mutations or trigger a synchronous re-render by updating state.\n\nAs far as scheduling, this works the same way as `componentDidMount` and `componentDidUpdate`. Your code runs immediately after the DOM has been updated, but before the browser has had a chance to \"paint\" those changes (the user doesn\\'t actually see the updates until after the browser has repainted).\n\n**Example:**\n\n```js\nimport React, { useState, useLayoutEffect } from 'react'\nimport ReactDOM from 'react-dom'\n\nconst BlinkyRender = () =\u003e {\n  const [value, setValue] = useState(0)\n\n  useLayoutEffect(() =\u003e {\n    if (value === 0) {\n      setValue(10 + Math.random() * 200)\n    }\n  }, [value])\n\n  console.log('render', value)\n\n  return (\n    \u003cdiv onClick={() =\u003e setValue(0)}\u003e\n      value: {value}\n    \u003c/div\u003e\n  )\n}\n\nReactDOM.render( \u003cBlinkyRender /\u003e, document.querySelector('#root'))\n```\n\n**useLayoutEffect vs useEffect:**\n\n* **useLayoutEffect**: If you need to mutate the DOM and/or do need to perform measurements\n* **useEffect**: If you don\\'t need to interact with the DOM at all or your DOM changes are unobservable (seriously, most of the time you should use this).\n\n**5. useDebugValue():**\n\n`useDebugValue()` can be used to display a label for custom hooks in React DevTools.\n\n**Example:**\n\n```js\nfunction useFriendStatus(friendID) {\n  const [isOnline, setIsOnline] = useState(null)\n\n  // ...\n\n  // Show a label in DevTools next to this Hook\n  // e.g. \"FriendStatus: Online\"\n  useDebugValue(isOnline ? 'Online' : 'Offline')\n\n  return isOnline\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between useEffect() and useLayoutEffect() hooks?\n\nThe main difference between the useEffect() hook and the useLayoutEffect() hook is that the useEffect() hook serves **asynchronously**, whereas the useLayoutEffect() hook works **synchronously**.\n\nAfter all DOM mutations have been completed by React, useLayoutEffect executes synchronously. If you need to measure the DOM (for example, to determine the scroll position or other styles for an element) and then modify the DOM or cause a synchronous re-render by changing the state, this can be helpful.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to Memoize Components in React?\n\nIf your component renders the same result given the same props, you can wrap it in a call to `React.memo` for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.\n\n`React.memo` only checks for prop changes. If your function component wrapped in `React.memo` has a `useState`, `useReducer` or `useContext` Hook in its implementation, it will still rerender when state or context change.\n\n**Example:** Let\\'s take an example of search functionality. In the example below, the App component contains:\n\n* Search input for the fruit name\n* A button and a child component where the user search will be displayed\n* A count of the number of times a user has clicked the button\n\n```js\nexport default function App() {\n   const fruits = [\"apple\", \"orange\", \"banana\"];\n   const [fruitName, setFruitName] = useState(\"\");\n   const [searchedFruit, setSearchedFruit] = useState(\n     \"Search your favorite fruit\"\n   );\n   const [count, setCount] = useState(0);\n   const searchFruitName = () =\u003e {\n     if (fruits.includes(fruitName)) {\n       setSearchedFruit(fruitName);\n     } else {\n       setSearchedFruit(\"No results Found\");\n     }\n     setCount(count+1);\n   };\n    const showAllFruits = () =\u003e {\n     return fruits.map((fruit, index) =\u003e {\n       return (\n         \u003cspan key={index} className=\"fruitname\"\u003e\n           {fruit}\n         \u003c/span\u003e\n       );\n     });\n   };\n   return (\n     \u003cdiv className=\"App\"\u003e\n       \u003ch3\u003eCount: {count}\u003c/h3\u003e\n       \u003cdiv className=\"fruits\"\u003e{showAllFruits()}\u003c/div\u003e\n       \u003cdiv\u003e\n         \u003cinput\n           type=\"text\"\n           placeholder=\"Search..\"\n           onChange={event =\u003e setFruitName(event.target.value)}\n           value={fruitName}\n         /\u003e\n         \u003cbutton onClick={searchFruitName}\u003eSearch\u003c/button\u003e\n       \u003c/div\u003e\n       \u003cSearchComponent searchedFruitName={searchedFruit} /\u003e\n     \u003c/div\u003e\n   );\n }\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-memo-yp7hb?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to prevent unnecessary updates using React.memo()?\n\nThe **React.memo()** is a higher-order component that will memoize your component, very similar to **PureComponent**. It will shallowly compare current and new props of the component, and if nothing changes, React will skip the rendering of that component.\n\n```js\n// Memo.js\n\nconst Text = (props) =\u003e {\n  console.log(`Text Component`);\n  return \u003cdiv\u003eText Component re-render: {props.count} times \u003c/div\u003e;\n};\n\nconst MemoText = React.memo(\n  (props) =\u003e {\n    console.log(`MemoText Component`);\n    return \u003cdiv\u003eMemoText Component re-render: {props.count} times \u003c/div\u003e;\n  },\n  (preprops, nextprops) =\u003e true\n);\n\n```\n\n```js\n// App.js\n\nconst App = () =\u003e {\n  console.log(`App Component`);\n  const [count, setCount] = useState(0);\n  return (\n    \u003c\u003e\n      \u003ch2\u003eThis is function component re-render: {count} times \u003c/h2\u003e\n      \u003cText count={count} /\u003e\n      \u003cMemoText count={count} /\u003e\n      \u003cbr /\u003e\n      \u003cbutton\n        onClick={() =\u003e {\n          setCount(count + 1);\n        }}\n      \u003e\n        CLICK ME\n      \u003c/button\u003e\n    \u003c/\u003e\n  );\n};\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/reactmomo-v85l8?file=/src/index.js:187-196)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 12. REACT CONTEXT\n\n\u003cbr/\u003e\n\n## Q. What is Context API in React?\n\nThe React Context API allows to easily access data at different levels of the component tree, without having to pass data down through `props`.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/context-api.jpg\" alt=\"Context API\" width=\"800px\" /\u003e\n\u003c/p\u003e\n\n**Example:**\n\n```js\n/**\n * Counter Component\n */\nconst { useState, useContext } = React;\n\nconst CountContext = React.createContext();\n\nfunction Counter() {\n  const { count, increase, decrease } = useContext(CountContext);\n  return (\n    \u003ch2\u003e\n      \u003cbutton onClick={decrease}\u003eDecrement\u003c/button\u003e\n      \u003cspan className=\"count\"\u003e{count}\u003c/span\u003e\n      \u003cbutton onClick={increase}\u003eIncrement\u003c/button\u003e\n    \u003c/h2\u003e\n  );\n}\n```\n\n```js\n/**\n * App Component\n */\nexport default function App() {\n  const [count, setCount] = useState(0);\n\n  const increase = () =\u003e {\n    setCount(count + 1);\n  };\n  const decrease = () =\u003e {\n    setCount(count - 1);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cCountContext.Provider value={{ count, increase, decrease }}\u003e\n        \u003cCounter /\u003e\n      \u003c/CountContext.Provider\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-context-api-v8syu?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you solve performance corner cases while using context?\n\nContext provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme (e.g. color, paddings, margins, font-sizes).\n\nContext API uses Context. Provider and Context. Consumer Components pass down the data but it is very cumbersome to write the long functional code to use this Context API. So useContext hook helps to make the code more readable, less verbose and removes the need to introduce Consumer Component. The useContext hook is the new addition in React 16.8.\n\n**Syntax:**\n\n```js\nconst authContext = useContext(initialValue);\n```\n\nThe useContext accepts the value provided by React.createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memorization.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of default value in context?\n\nThe **defaultValue** argument is **only** used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Passing **undefined** as a Provider value does not cause consuming components to use **defaultValue**.\n\n```js\n/**\n * Default value in Context API\n */\nimport { createContext, useContext } from \"react\";\n\nconst Context = createContext(\"Default Value\");\n\n/**\n * Child1 Component\n */\nfunction Child1() {\n  const context = useContext(Context);\n  return \u003ch2\u003eChild1: {context}\u003c/h2\u003e;\n}\n\n/**\n * Child2 Component\n */\nfunction Child2() {\n  const context = useContext(Context);\n  return \u003ch2\u003eChild2: {context}\u003c/h2\u003e;\n}\n\n/**\n * App Component\n */\nexport default function App() {\n  return (\n    \u003c\u003e\n      \u003cContext.Provider value={\"Initial Value\"}\u003e\n        \u003cChild1 /\u003e {/* Child inside Provider will get \"Initial Value\" */}\n      \u003c/Context.Provider\u003e\n      \u003cChild2 /\u003e {/* Child outside Provider will get \"Default Value\" */}\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-default-value-in-context-1vh1c)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use contextType react?\n\nThe **ContextType** property on a **class component** can be assigned a Context object created by `React.createContext()` method. This property lets you consume the nearest current value of the context using `this.context`. We can access `this.context` in any lifecycle method including the render functions.\n\n**Example:**\n\n```js\n/**\n * ContextType()\n */\nimport React, { Component } from \"react\";\nimport ReactDOM from \"react-dom\";\n\nconst MyContext = React.createContext({\n  name: \"Context Type\"\n});\n\nconst { Provider, Consumer } = MyContext;\n\n/**\n * StoreProvider Component\n */\nclass StoreProvider extends Component {\n  state = {\n    count: 0\n  };\n\n  incrementCount = () =\u003e {\n    console.log(\"Increment\");\n    const { count } = this.state;\n    this.setState({ count: count + 1 });\n  };\n\n  render() {\n    return (\n      \u003cProvider\n        value={{\n          state: this.state,\n          incrementCount: this.incrementCount\n        }}\n      \u003e\n        {this.props.children}\n      \u003c/Provider\u003e\n    );\n  }\n}\n\n/**\n * VoteCount Component\n */\nclass VoteCount extends Component {\n  static contextType = MyContext;\n\n  render() {\n    const { state, incrementCount } = this.context;\n\n    return (\n      \u003cdiv\u003e\n        \u003cbutton onClick={incrementCount}\u003eClick Me\u003c/button\u003e {state.count}\n      \u003c/div\u003e\n    );\n  }\n}\n\nconst rootElement = document.getElementById(\"root\");\nReactDOM.render(\n  \u003cStoreProvider\u003e\n    \u003cVoteCount /\u003e\n  \u003c/StoreProvider\u003e,\n  rootElement\n);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-contexttype-q4l4pg?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to update React Context from inside a child component?\n\nThe Context API allows data storage and makes it accessible to any child component who want to use it. This is valid whatever level of component graph the children is in.\n\n**Example:**\n\n```js\n/**\n * React Context API\n */\nimport React, { useState, useContext } from \"react\";\nconst MyContext = React.createContext();\n\n/**\n * Child Component\n */\nconst MyComponent = () =\u003e {\n  const { count, increment } = useContext(MyContext);\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={increment}\u003eClick Me\u003c/button\u003e {count}\n    \u003c/div\u003e\n  );\n};\n\n/**\n * App Component\n */\nexport default function App() {\n  const [count, updateCount] = useState(0);\n  function increment() {\n    updateCount(count + 1);\n  }\n\n  return (\n    \u003cMyContext.Provider value={{ count, increment }}\u003e\n      \u003cdiv\u003e\n        \u003cMyComponent /\u003e\n      \u003c/div\u003e\n    \u003c/MyContext.Provider\u003e\n  );\n}\n```\n\nHere, We are storing data in component state in which we want to use context and we created a function that modify this state. We pass the state and function as context values. It then become possible from the child to get the function and to use it to update your context.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-context-api-kdd2v0?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is prop drilling and how can you avoid it?\n\nReact passes data to child components via props from top to bottom. While there are few props or child components, it is easy to manage and pass down data. But when the application grows, and want to pass data from the top level component to a 3rd or 4th level level component but we end up passing these data to components on each level of the tree. This is called **Prop-drilling**.\n\n**Using Context API:**  \n\nThe Context API solves some of these prop drilling problems. It let pass data to all of the components in the tree without writing them manually in each of them. Shared data can be anything: state, functions, objects, we name it, and it is accessible to all nested levels that are in the scope of the context.\n\n**Example:**\n\n```js\n/**\n * Prop Drilling\n */\nimport React, { useContext, createContext } from \"react\";\n\n// It returns an object with 2 values:\n// { Provider, Consumer }\nconst NumberContext = createContext();\n\nfunction Display() {\n  const value = useContext(NumberContext);\n  return \u003ch3\u003eContex Value: {value}\u003c/h3\u003e;\n}\n\nexport default function App() {\n  // Use the Provider to make a value available to all\n  // children and grandchildren\n  return (\n    \u003cNumberContext.Provider value={100}\u003e\n      \u003cdiv\u003e\n        \u003cDisplay /\u003e\n      \u003c/div\u003e\n    \u003c/NumberContext.Provider\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-prop-drilling-knowbp?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 13. REACT ROUTER\n\n\u003cbr/\u003e\n\n## Q. What is React Router?\n\nReact router enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. It has a simple API with powerful features like lazy loading, dynamic route matching, and location transition handling.\n\n```js\n/**\n * React Router v6\n */\nimport { BrowserRouter, Route, Routes, NavLink } from \"react-router-dom\";\n\n/**\n * Home Component\n */\nconst Home = () =\u003e {\n  return \u003ch1\u003eHome Page\u003c/h1\u003e;\n};\n\n/**\n * Contacts Component\n */\nconst Contacts = () =\u003e {\n  return \u003ch1\u003eContact Page\u003c/h1\u003e;\n};\n\n/**\n * App Component\n */\nexport default function App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cBrowserRouter\u003e\n        \u003cdiv className=\"navbar\"\u003e\n          \u003cNavLink to={\"/\"}\u003eHome\u003c/NavLink\u003e\n          \u003cNavLink to={\"/contact\"}\u003eContact Us\u003c/NavLink\u003e\n        \u003c/div\u003e\n        \u003cRoutes\u003e\n          \u003cRoute path=\"/\" element={\u003cHome /\u003e} /\u003e\n          \u003cRoute path=\"/contact\" element={\u003cContacts /\u003e} /\u003e\n        \u003c/Routes\u003e\n      \u003c/BrowserRouter\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-router-v6-xuycsq?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the components of react router?\n\nThe main components of React router are\n\n**1. BrowserRouter**:\n\nBrowserRouter is a router implementation that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.\n\n**2. Routes**:\n\nIt\\'s a new component introduced in the v6 and a upgrade of the component. The main advantages of Routes over Switch that routes are chosen based on the best match instead of being traversed in order.\n\n**3. Route**:\n\nRoute is the conditionally shown component that renders some UI when its path matches the current URL.\n\n**4. Link**:\n\nLink component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between NavLink and Link?\n\nThe `\u003cLink\u003e` component is used to navigate the different routes on the site. But `\u003cNavLink\u003e` is used to add the style attributes to the active routes.\n\n**Link:**\n\n```js\n\u003cLink to=\"/\"\u003eHome\u003c/Link\u003e\n```\n\n**NavLink:**\n\n```js\n\u003cNavLink to=\"/\" activeClassName=\"active\"\u003eHome\u003c/NavLink\u003e\n```\n\n**Example:**\n\nindex.css\n\n```css\n.active {\n  color: blue;\n}\n```\n\nRoutes.js\n\n```js\nimport ReactDOM from 'react-dom'\nimport './index.css'\nimport { Route, NavLink, BrowserRouter as Router, Switch } from 'react-router-dom'\nimport App from './App'\nimport Users from './users'\nimport Contact from './contact'\nimport Notfound from './notfound'\n\nconst Routes = (\n  \u003cRouter\u003e\n    \u003cdiv\u003e\n      \u003cul\u003e\n        \u003cli\u003e\n          \u003cNavLink exact activeClassName=\"active\" to=\"/\"\u003e\n            Home\n          \u003c/NavLink\u003e\n        \u003c/li\u003e\n        \u003cli\u003e\n          \u003cNavLink activeClassName=\"active\" to=\"/users\"\u003e\n            Users\n          \u003c/NavLink\u003e\n        \u003c/li\u003e\n        \u003cli\u003e\n          \u003cNavLink activeClassName=\"active\" to=\"/contact\"\u003e\n            Contact\n          \u003c/NavLink\u003e\n        \u003c/li\u003e\n      \u003c/ul\u003e\n      \u003chr /\u003e\n      \u003cSwitch\u003e\n        \u003cRoute exact path=\"/\" component={App} /\u003e\n        \u003cRoute path=\"/users\" component={Users} /\u003e\n        \u003cRoute path=\"/contact\" component={Contact} /\u003e\n        \u003cRoute component={Notfound} /\u003e\n      \u003c/Switch\u003e\n    \u003c/div\u003e\n  \u003c/Router\u003e\n)\n\nReactDOM.render(Routes, document.getElementById('root'))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is withRouter for in react-router-dom?\n\n`withRouter()` is a higher-order component that allows to get access to the `history` object\\'s properties and the closest `\u003cRoute\u003e`\\'s match. `withRouter` will pass updated `match`, `location`, and `history` props to the wrapped component whenever it renders.\n\n**Example:**\n\n```js\nimport React from \"react\"\nimport PropTypes from \"prop-types\"\nimport { withRouter } from \"react-router\"\n\n// A simple component that shows the pathname of the current location\nclass ShowTheLocation extends React.Component {\n  static propTypes = {\n    match: PropTypes.object.isRequired,\n    location: PropTypes.object.isRequired,\n    history: PropTypes.object.isRequired\n  }\n\n  render() {\n    const { match, location, history } = this.props\n\n    return \u003cdiv\u003eYou are now at {location.pathname}\u003c/div\u003e\n  }\n}\n\nconst ShowTheLocationWithRouter = withRouter(ShowTheLocation)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How React Router is different from history library?\n\nReact Router is a wrapper around the history library which handles interaction with the browser\\'s `window.history` with its browser and hash histories. React Router provides two API\\'s\n\n* BrowserRouter\n* HashRouter\n\n```js\n// \u003cBrowserRouter\u003e\nhttp://example.com/about\n\n// \u003cHashRouter\u003e\nhttp://example.com/#/about\n```\n\nThe `\u003cBrowserRouter\u003e` is the more popular of the two because it uses the HTML5 History API to keep your UI in sync with the URL, whereas the `\u003cHashRouter\u003e` uses the hash portion of the URL (`window.location.hash`). If you need to support legacy browsers that don\\'t support the History API, you should use `\u003cHashRouter\u003e`. Otherwise `\u003cBrowserRouter\u003e` is the better choice for most use cases.\n\n**Example:**\n\n```js\n// src/index.js\n\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport App from \"./App\";\nimport { BrowserRouter } from \"react-router-dom\";\n\nReactDOM.render(\n  \u003cBrowserRouter\u003e\n    \u003cApp /\u003e\n  \u003c/BrowserRouter\u003e,\n  document.getElementById(\"root\")\n);\n```\n\nThe above code creates a history instance for our entire `\u003cApp\u003e` component. Each `\u003cRouter\u003e` component creates a history object that keeps track of the current location (`history.location`) and also the previous locations in a stack. The history object has methods such as `history.push`, `history.replace`, `history.goBack`, `history.goForward` etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use useNavigate() in React Router v6?\n\nThe **useNavigate()** hook is introduced in React Router v6 to replace the `useHistory()` hook. In the earlier version, the `useHistory()` hook accesses the React Router history object and navigates to the other routers using the push() or replace() methods.\n\nThe `useNavigate()` hook returns a function that lets you navigate programmatically, for example after a form is submitted. If using `replace: true`, the navigation will replace the current entry in the history stack instead of adding a new one.\n\n```js\n/**\n * useNavigate()\n */\nimport React from \"react\";\nimport { NavLink, Link, Routes, Route,  useParams, useNavigate } from \"react-router-dom\";\nimport \"./styles.css\";\n\nfunction Home() {\n  return \u003ch1\u003eHome Page\u003c/h1\u003e;\n}\n\nfunction Users() {\n  return (\n    \u003cul\u003e\n      \u003cli\u003e\u003cLink to={\"/users/1\"}\u003eUser 1\u003c/Link\u003e\u003c/li\u003e\n    \u003c/ul\u003e\n  );\n}\n\nfunction UserDetail() {\n  let { id } = useParams();\n  let navigate = useNavigate();\n\n  function handleClick() {\n    navigate(\"/users\");\n  }\n  return (\n    \u003c\u003e\n      \u003ch1\u003eUser Details Page: {id}\u003c/h1\u003e\n      \u003cbutton onClick={handleClick}\u003eBack\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n\nfunction AppRoutes() {\n  return (\n    \u003cRoutes\u003e\n      \u003cRoute path=\"/\" element={\u003cHome /\u003e} /\u003e\n      \u003cRoute path=\"users\" element={\u003cUsers /\u003e} /\u003e\n      \u003cRoute path=\"users/:id\" element={\u003cUserDetail /\u003e} /\u003e\n    \u003c/Routes\u003e\n  );\n}\n\nexport default function App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cnav\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cNavLink to=\"/\" end\u003eHome Page\u003c/NavLink\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cNavLink to=\"/users\"\u003eUsers Page\u003c/NavLink\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n      \u003c/nav\u003e\n      \u003cAppRoutes /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/cool-paper-vxgn15?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to get parameter value from query string?\n\nIn order to get query parameters from the URL, we can use **URLSearchParams**. In simple words, URLSearchParams is a defined interface, implemented by modern browsers, that allows us to work with the query string. It does not require React Router or even React itself.\n\n**Example:**\n\n```js\n// http://localhost:3000/?id=100\u0026name=react\n\nconst queryParams = new URLSearchParams(window.location.search);\n\nconst id = queryParams.get('id');\nconst name = queryParams.get('name');\n\nconsole.log(id, name); // 100 react\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-query-parameters-yqx7e?file=/src/ParamsExample.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to access history object in React Router v6?\n\nThe **useNavigate()** hook has been added to React Router v6 to replace the `useHistory()` hook.\n\n**Example:**\n\n```js\n/**\n * React Router\n */\nimport { BrowserRouter, Routes, NavLink, Route, useParams, useNavigate } from \"react-router-dom\";\n\nexport default function App() {\n  return (\n    \u003cBrowserRouter\u003e\n      \u003cdiv\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cNavLink to=\"/\"\u003eHome\u003c/NavLink\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cNavLink to=\"/user/Bhavya/bhavyasingh@email.com\"\u003eUser Profile\u003c/NavLink\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n        \u003cRoutes\u003e\n          \u003cRoute path=\"/user/:name/:email\" element={\u003cUser /\u003e} /\u003e\n          \u003cRoute path=\"/\" element={\u003cHome /\u003e} /\u003e\n        \u003c/Routes\u003e\n        \u003cHomeButton /\u003e\n      \u003c/div\u003e\n    \u003c/BrowserRouter\u003e\n  );\n}\n\nfunction Home() {\n  return \u003ch2\u003eWelcome Home\u003c/h2\u003e;\n}\n\nfunction User() {\n  let { name, email } = useParams();\n  return (\n    \u003ch2\u003eName: {name} \u003cbr /\u003e Email: {email}\u003c/h2\u003e\n  );\n}\n\nfunction HomeButton() {\n  const history = useNavigate();\n\n  function handleClick() {\n    history(\"/\");\n  }\n\n  return (\n    \u003c\u003e\n      \u003cbutton type=\"button\" onClick={handleClick}\u003eGo Home\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usenavigate-j5fkzn?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to perform automatic redirect in React.js?\n\nIn contrast to the Navigate component and its declarative redirect, we can perform a programmatic redirect by using React Router\\'s **useNavigate()** Hook:\n\n**Example:**\n\n```js\n/**\n * Automatic Redirect in router-v6\n */\nimport { NavLink, BrowserRouter, Routes, Route, Navigate } from \"react-router-dom\";\n\nexport default function App() {\n  return (\n    \u003cBrowserRouter\u003e\n      \u003cnav style={{ display: \"flex\", flexDirection: \"row\", gap: \"1em\" }}\u003e\n        \u003cNavLink to=\"/\" children=\"Home\" /\u003e\n        \u003cNavLink to=\"/about\" children=\"About\" /\u003e\n        \u003cNavLink to=\"/help\" children=\"Help\" /\u003e\n      \u003c/nav\u003e\n      \u003cRoutes\u003e\n        \u003cRoute index element={\u003cNavigate replace to=\"home\" /\u003e} /\u003e\n        \u003cRoute path=\"home\" element={\u003ch1\u003eHome Page\u003c/h1\u003e} /\u003e\n        \u003cRoute path=\"about\" element={\u003ch1\u003eAbout Page\u003c/h1\u003e} /\u003e\n        \u003cRoute path=\"help\" element={\u003ch1\u003eHelp Page\u003c/h1\u003e} /\u003e\n      \u003c/Routes\u003e\n    \u003c/BrowserRouter\u003e\n  );\n}\n```\n\n*Note: To keep the history clean, you should set `replace` prop. This will avoid extra redirects after the user click back.*\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-automatic-redirect-odw0yn?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to pass additional data while redirecting to a route in React?\n\n**Using Link:**\n\n**Example:**\n\n```js\n/**\n * Pass additional data while redirecting\n */\nimport { BrowserRouter, Link, Route, Routes, useLocation } from \"react-router-dom\";\n\n/**\n * View User Component\n */\nfunction ViewUser() {\n  const location = useLocation();\n  return (\n    \u003c\u003e\n      \u003ch2\u003eUser Details\u003c/h2\u003e\n      \u003cdiv\u003eName:{location.state.name}\u003c/div\u003e\n      \u003cdiv\u003eEmail:{location.state.email}\u003c/div\u003e\n    \u003c/\u003e\n  );\n}\n\n/**\n * User Component\n */\nfunction User() {\n  return (\n    \u003cdiv\u003e\n      \u003ch2\u003ePass additional data while redirecting\u003c/h2\u003e\n      \u003cLink\n        to=\"/view-user\"\n        state={{\n          name: \"Kalini Khalsa\",\n          email: \"kalini.khalsa@email.com\"\n        }}\n      \u003e\n        \u003cbutton\u003eView User\u003c/button\u003e\n      \u003c/Link\u003e\n    \u003c/div\u003e\n  );\n}\n\n/**\n * App Component\n */\nexport default function App() {\n  return (\n    \u003cBrowserRouter\u003e\n      \u003cRoutes\u003e\n        \u003cRoute exact path=\"/\" element={\u003cUser /\u003e} /\u003e\n        \u003cRoute exact path=\"/user\" element={\u003cUser /\u003e} /\u003e\n        \u003cRoute exact path=\"/view-user\" element={\u003cViewUser /\u003e} /\u003e\n      \u003c/Routes\u003e\n    \u003c/BrowserRouter\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-pass-data-using-router-br5kdb?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to pass props in React router v6?\n\nReact Router uses a declarative, component-based approach to routing. `Route` allows you to map URL paths to different React components.\n\n**Example:**\n\n```js\n/**\n * Pass props in React Router-v6\n */\nimport React from \"react\";\nimport { BrowserRouter, Routes, Route, NavLink } from \"react-router-dom\";\n\nexport function Greeting(props) {\n  const { text } = props;\n  return (\n    \u003c\u003e\n      \u003ch2\u003eGreetings Page\u003c/h2\u003e\n      \u003cp\u003e{text}\u003c/p\u003e\n    \u003c/\u003e\n  );\n}\n\nconst RouterExample = () =\u003e \u003ch2\u003eHome Page\u003c/h2\u003e;\n\nconst App = () =\u003e (\n  \u003cBrowserRouter\u003e\n    \u003cul\u003e\n      \u003cli\u003e\u003cNavLink to=\"/\"\u003eHome\u003c/NavLink\u003e\u003c/li\u003e\n      \u003cli\u003e\u003cNavLink to=\"/greeting/pradeep\"\u003eGreeting\u003c/NavLink\u003e\u003c/li\u003e\n    \u003c/ul\u003e\n    \u003chr /\u003e\n    \u003cRoutes\u003e\n      \u003cRoute exact path=\"/\" element={\u003cRouterExample /\u003e} /\u003e\n      \u003cRoute path=\"/greeting/:name\" element={\u003cGreeting text=\"Hello World\" /\u003e} /\u003e\n    \u003c/Routes\u003e\n  \u003c/BrowserRouter\u003e\n);\n\nexport default App;\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-pass-props-in-router-g9zjg4?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to get query parameters in react routing?\n\n**Using `useParams()`**\n\n**Example:**\n\n```js\n/**\n * useParams()\n */\nimport React from \"react\";\nimport { BrowserRouter, Route, Routes, Link, useParams } from \"react-router-dom\";\n\nexport default function App() {\n  return (\n    \u003cBrowserRouter\u003e\n      \u003cdiv\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cLink to=\"/home\"\u003eHome\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/contact-us\"\u003eContact Us\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/help\"\u003eHelp\u003c/Link\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n        \u003cRoutes\u003e\n          \u003cRoute path=\"/:id\" element={\u003cChild /\u003e} /\u003e\n        \u003c/Routes\u003e\n      \u003c/div\u003e\n    \u003c/BrowserRouter\u003e\n  );\n}\n\nfunction Child() {\n  // `useParams` hook used here to access parameters\n  let { id } = useParams();\n\n  return \u003ch2\u003eParameter: {id}\u003c/h2\u003e;\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-get-query-parameters-ngsm3l?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between HashRouter and BrowserRouter in React?\n\n**1. BrowserRouter:**\n\n* The widely popular router and a router for modern browsers which user HTML5 pushState API. (i.e. `pushState`, `replaceState` and `popState` API).\n* It routes as normal URL in browser, you can\\'t differentiate whether it is server rendered page or client rendered page through the URL.\n* It assumes, your server handles all the request URL (eg., `/`, `/about`) and points to root `index.html`. From there, BrowserRouter take care of routing the relevant page.\n* It accepts `forceRefresh` props to support legacy browsers which doesn\\'t support HTML5 pushState API\n\n**Syntax:**\n\n```js\n/**\n * https://example.com/home\n * https://example.com/about\n */\n\n\u003cBrowserRouter\n  basename={optionalString}\n  forceRefresh={optionalBool}\n  getUserConfirmation={optionalFunc}\n  keyLength={optionalNumber}\n\u003e\n  \u003cApp /\u003e\n\u003c/BrowserRouter\u003e\n```\n\n**Example:**\n\n```js\n/**\n * BrowserRouter()\n */\nimport { Link, BrowserRouter, Routes, Route } from \"react-router-dom\";\n\nconst HomePage = () =\u003e {\n  return \u003ch2\u003eHome Page\u003c/h2\u003e;\n};\n\nconst AboutPage = () =\u003e {\n  return \u003ch2\u003eAbout Page\u003c/h2\u003e;\n};\n\nexport default function App() {\n  return (\n    \u003csection className=\"App\"\u003e\n      \u003cBrowserRouter\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cLink to=\"/home\"\u003eHome\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/about\"\u003eAbout\u003c/Link\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n        \u003cRoutes\u003e\n          \u003cRoute exact path=\"/home\" element={\u003cHomePage /\u003e} /\u003e\n          \u003cRoute exact path=\"/about\" element={\u003cAboutPage /\u003e} /\u003e\n        \u003c/Routes\u003e\n      \u003c/BrowserRouter\u003e\n    \u003c/section\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-browserrouter-53zjvx?file=/src/App.js)**\n\n**2. HashRouter:**\n\n* A router which uses client side hash routing.\n* Whenever, there is a new route get rendered, it updated the browser URL with hash routes. (eg., `/#/about`)\n* Hash portion of the URL won\\'t be handled by server, server will always send the `index.html` for every request and ignore hash value. Hash value will be handled by react router.\n* It is used to support legacy browsers which usually doesn\\'t support HTML `pushState` API\n\n**Syntax:**\n\n```js\n/**\n * https://example.com/#/home\n * https://example.com/#/about\n */\n\n\u003cHashRouter\n  basename={optionalString}\n  getUserConfirmation={optionalFunc}\n  hashType={optionalString}\n\u003e\n  \u003cApp /\u003e\n\u003c/HashRouter\u003e\n```\n\n**Example:**\n\n```js\n/**\n * HashRouter()\n */\nimport { Link, HashRouter, Routes, Route } from \"react-router-dom\";\n\nconst HomePage = () =\u003e {\n  return \u003ch2\u003eHome Page\u003c/h2\u003e;\n};\n\nconst AboutPage = () =\u003e {\n  return \u003ch2\u003eAbout Page\u003c/h2\u003e;\n};\n\nexport default function App() {\n  return (\n    \u003csection className=\"App\"\u003e\n      \u003cHashRouter\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003cLink to=\"/home\"\u003eHome\u003c/Link\u003e\u003c/li\u003e\n          \u003cli\u003e\u003cLink to=\"/about\"\u003eAbout\u003c/Link\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n        \u003cRoutes\u003e\n          \u003cRoute exact path=\"/home\" element={\u003cHomePage /\u003e} /\u003e\n          \u003cRoute exact path=\"/about\" element={\u003cAboutPage /\u003e} /\u003e\n        \u003c/Routes\u003e\n      \u003c/HashRouter\u003e\n    \u003c/section\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-hashrouter-pcn4dj?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is route based code splitting?\n\nRoute based code splitting is essential during the page transitions on the web, which takes some amount of time to load. Here is an example of how to setup route-based code splitting into the app using React Router with `React.lazy`.\n\n**Example:**\n\n```js\n/**\n * Lazy Loading\n */\nimport React, { Suspense, lazy } from \"react\";\nimport { BrowserRouter, Routes, Route } from \"react-router-dom\";\n\nconst Home = lazy(() =\u003e import(\"./Home\"));\nconst About = lazy(() =\u003e import(\"./About\"));\n\nexport default function App() {\n  return (\n    \u003cBrowserRouter\u003e\n      \u003cSuspense fallback={\u003cdiv\u003eLoading...\u003c/div\u003e}\u003e\n        \u003cRoutes\u003e\n          \u003cRoute exact path=\"/\" element={\u003cHome /\u003e} /\u003e\n          \u003cRoute path=\"/about\" element={\u003cAbout /\u003e} /\u003e\n        \u003c/Routes\u003e\n      \u003c/Suspense\u003e\n    \u003c/BrowserRouter\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-route-based-code-splitting-s2uq6n?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is lazy function in React?\n\n`React.lazy()` makes it easy to create components that are loaded using dynamic `import()` but are rendered like regular components. This will automatically cause the bundle containing the component to be loaded when the component is rendered.\n\n`React.lazy()` takes a function as its argument that must return a promise by calling `import()` to load the component. The returned Promise resolves to a module with a default export containing the React component.\n\n**Example:**\n\n```js\nimport React, { lazy } from 'react'\n\nconst MyComponent = React.lazy(() =\u003e import('./MyComponent'))\n\nconst App = () =\u003e {\n  \u003cdiv\u003e\n    \u003cMyComponent /\u003e\n  \u003c/div\u003e\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is code-splitting?\n\nCode-Splitting is a feature supported by bundlers like **Webpack**, **Rollup** and **Browserify** ( via factor-bundle ) which can create multiple bundles that can be dynamically loaded at runtime.\n\nCode splitting uses `React.lazy` and `Suspense` library, which helps to load a dependency lazily and only load it when needed by the user. The code splitting improves:\n\n* The performance of the app\n* The impact on memory\n* The downloaded Kilobytes (or Megabytes) size\n\n**React.lazy and Suspense:**\n\nThe `React.lazy` function allows us to render a dynamic import as a regular component. The `suspense` component is responsible for handling the output when the lazy component is fetched and rendered.\n\n**Example:**\n\n```js\nimport React, { Suspense } from 'react';\n\nconst UsersComponent = React.lazy(() =\u003e import('./UsersComponent'));\n\nfunction MyComponent() {\n  return (\n    \u003cdiv\u003e\n      \u003cSuspense fallback={\u003cdiv\u003eLoading...\u003c/div\u003e}\u003e\n        \u003cUsersComponent /\u003e\n      \u003c/Suspense\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is dynamic import in react?\n\n`React.lazy` takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.\n\nThe lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we\\'re waiting for the lazy component to load.\n\n**Example:**\n\n```js\nimport React, { Suspense } from 'react';\n\nconst UsersComponent = React.lazy(() =\u003e import('./UsersComponent'));\n\nfunction MyComponent() {\n  return (\n    \u003cdiv\u003e\n      \u003cSuspense fallback={\u003cdiv\u003eLoading...\u003c/div\u003e}\u003e\n        \u003cUsersComponent /\u003e\n      \u003c/Suspense\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are loadable components?\n\nIf you want to do code-splitting in a server rendered app, it is recommend to use Loadable Components because `React.lazy` and `Suspense` is not available for server-side rendering. Loadable lets you render a dynamic import as a regular component.\n\n**Installation:**\n\n```js\nnpm install @loadable/component\n```\n\n**Example:**\n\n```js\nimport loadable from '@loadable/component'\n\nconst UsersComponent = loadable(() =\u003e import('./UsersComponent'))\n\nfunction MyComponent() {\n  return (\n    \u003cdiv\u003e\n      \u003cUsersComponent /\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 14. REACT ERROR BOUNDARIES\n\n\u003cbr/\u003e\n\n## Q. What are error boundaries in React?\n\nError boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.\n\nUse **static getDerivedStateFromError()** to render a fallback UI after an error has been thrown. Use **componentDidCatch()** to log error information.\n\n**Syntax:**\n\n```js\n\u003cErrorBoundary\u003e\n   \u003cUser/\u003e\n\u003c/ErrorBoundary\u003e\n```\n\n**Example:**\n\n```js\n/**\n * ErrorBoundary Component\n */\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  static getDerivedStateFromError(error) {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  componentDidCatch(error, errorInfo) {\n    // You can also log the error to an error reporting service\n    logErrorToMyService(error, errorInfo);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      // You can render any custom fallback UI\n      return \u003ch1\u003eSomething went wrong.\u003c/h1\u003e;\n    }\n\n    return this.props.children; \n  }\n}\n```\n\nHere, We have a state object having two variables `isErrorOccured` and `errorMessage` which will be updated to true if any error occurs.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-error-boundary-pfj9vt?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between try catch block and error boundaries?\n\n**1. Try…catch** is used in specific code blocks where you program the functionality of the application.\n\n```js\ntry {\n  // Some Calculation\n} catch (error) {\n  console.log(`Error: ${error}`);\n}\n```\n\n**2. Error Boundaries** deal with declarative code. Imperative programming is how you do something and declarative programming is what you do.\n\nWith error boundary, if there is an error, you can trigger a fallback UI; whereas, with `try…catch`, you can catch errors in your code.\n\n```js\nimport ErrorBoundary from \"error-boundary\";\n\nfunction Users() {\n  return (\n    \u003cdiv\u003e\n      \u003cErrorBoundary\u003e\n        \u003cUsers /\u003e\n      \u003c/ErrorBoundary\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-vendor-prefix-k29wi?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the benefit of component stack trace from error boundary?\n\nComponent Stack Trace prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. It also display the filenames and line numbers in the component stack trace.\n\n**Example:**\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/stack-trace.png\" alt=\"Component Stack Trace\" /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the methods invoked during error handling?\n\nTo create an error boundary, we simply have to create a class component and define a state variable for determining whether the error boundary has caught an error. Our class component should also have at least three methods:\n\n* A static method called **getDerivedStateFromError()**, which is used to update the error boundary\\'s state\n* A **componentDidCatch()** lifecycle method for performing operations when our error boundaries catch an error, such as logging to an error logging service\n* A **render()** method for rendering our error boundary\\'s child or the fallback UI in case of an error\n\n**Example:**\n\n```js\n/**\n * Error Boundary in React\n */\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  static getDerivedStateFromError(error) {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  componentDidCatch(error, errorInfo) {\n    // You can also log the error to an error reporting service\n    logErrorToMyService(error, errorInfo);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      // You can render any custom fallback UI\n      return \u003ch1\u003eSomething went wrong.\u003c/h1\u003e;\n    }\n\n    return this.props.children; \n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 15. REACT REFS\n\n\u003cbr/\u003e\n\n## Q. What do you understand by refs in React?\n\nThe **Refs** provide a way to access DOM nodes or React elements created in the render method. React `Refs` are a useful feature that act as a means to reference a DOM element or a class component from within a parent component.\n\nRefs also provide some flexibility for referencing elements within a child component from a parent component, in the form of **ref forwarding**.\n\n**Example:**\n\n```javascript\n/**\n * Refs\n */\nclass App extends React.Component {\n    constructor(props) {\n      super(props)\n      // create a ref to store the textInput DOM element\n      this.textInput = React.createRef()\n      this.state = {\n        value: ''\n      }\n    }\n  \n  // Set the state for the ref\n  handleSubmit = e =\u003e {\n    e.preventDefault()\n    this.setState({ value: this.textInput.current.value })\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eReact Ref - createRef\u003c/h1\u003e\n         {/** This is what will update **/}\n        \u003ch3\u003eValue: {this.state.value}\u003c/h3\u003e\n        \u003cform onSubmit={this.handleSubmit}\u003e\n          {/** Call the ref on \u003cinput\u003e so we can use it to update the \u003ch3\u003e value **/}\n          \u003cinput type=\"text\" ref={this.textInput} /\u003e\n          \u003cbutton\u003eSubmit\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n**When to Use Refs:**  \n\n* Managing focus, text selection, or media playback.\n* Triggering imperative animations.\n* Integrating with third-party DOM libraries.\n\n**When not to use refs:**  \n\n* Should not be used with functional components because they dont have instances.\n* Not to be used on things that can be done declaritvely.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can I use multiple refs for an array of elements with hooks?\n\n**Example:**\n\n```js\n/**\n * Multiple Refs\n */\nimport React, { useRef } from \"react\";\n\nexport default function App() {\n  const arr = [10, 20, 30];\n  // multiple refs\n  const refs = useRef([]); \n\n  return (\n    \u003cdiv\u003e\n      {arr.map((item, index) =\u003e {\n        return (\n          \u003cdiv\n            key={index}\n            ref={(element) =\u003e {\n              refs.current[index] = element;\n            }}\n          \u003e\n            {item}\n          \u003c/div\u003e\n        );\n      })}\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-multiple-refs-z2wqm?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between useRef() and createRef()?\n\n**1. useRef():**\n\nThe useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn\\'t create a new instance of the ref for every re-render. It persists the existing ref between re-renders.\n\n**Example:**\n\n```js\n/**\n * useRef()\n */\nexport default function App() {\n  const [count, setCount] = useState(0);\n  const ref = useRef();\n\n  useEffect(() =\u003e {\n    ref.current = \"SomeInitialValue\";\n  }, []);\n\n  useEffect(() =\u003e {\n    console.log(count, ref.current);\n  }, [count]);\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cbutton onClick={() =\u003e setCount((c) =\u003e c + 1)}\u003eIncrement\u003c/button\u003e\n      \u003cp\u003e{count}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-useref-44wfd?file=/src/App.js)**\n\n**2. createRef():**\n\nThe createRef is a function that creates a new ref every time. Unlike the useRef, it does not save its value between re-renders, instead creates a new instance of the ref for every re-render. Thus implying that it does not persist the existing ref between re-renders.\n\n**Example:**\n\n```js\n/**\n * createRef()\n */\nexport default function App() {\n  const [count, setCount] = useState(0);\n  const ref = createRef();\n\n  useEffect(() =\u003e {\n    ref.current = \"SomeInitialValue\";\n  }, []);\n\n  useEffect(() =\u003e {\n    console.log(count, ref.current);\n  }, [count]);\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cbutton onClick={() =\u003e setCount((c) =\u003e c + 1)}\u003eIncrement\u003c/button\u003e\n      \u003cp\u003e{count}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-createref-pgu2x?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why are inline ref callback or function not recommended?\n\nIf **ref callback** is defined as an inline function, it will get called twice during updates, first with `null` and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.\n\n**Example:**\n\n```js\n/**\n * Inline Ref Callback()\n */\nimport React from \"react\";\n\nexport default class App extends React.Component {\n  handleSubmit = (e) =\u003e {\n    e.preventDefault();\n    console.log(\"Input Value is: \" + this.input.value);\n  };\n  render() {\n    return (\n      \u003cform onSubmit={(e) =\u003e this.handleSubmit(e)}\u003e\n        \u003cinput type=\"text\" ref={(input) =\u003e (this.input = input)} /\u003e\n        \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n      \u003c/form\u003e\n    );\n  }\n}\n```\n\nHere, When the `\u003cinput\u003e` element is rendered, React calls the function defined in the ref attribute, passing that function the `\u003cinput\u003e` element as an argument.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-ref-callback-6ry5o?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Which is the preferred option callback refs or findDOMNode()?\n\nIt is preferred to use **callback refs** over `findDOMNode()` API. Because `findDOMNode()` prevents certain improvements in React in the future.\n\nThe legacy approach of using `findDOMNode()`:\n\n```js\nclass MyComponent extends Component {\n  componentDidMount() {\n    findDOMNode(this).scrollIntoView()\n  }\n\n  render() {\n    return \u003cdiv /\u003e\n  }\n}\n```\n\nThe recommended approach is:\n\n```js\nclass MyComponent extends Component {\n  componentDidMount() {\n    this.node.scrollIntoView()\n  }\n\n  render() {\n    return \u003cdiv ref={node =\u003e this.node = node} /\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set focus on an input field after rendering?\n\nRefs can be used to access DOM nodes or React components that are rendered in the render method. Refs are created with `React.createRef()` function. Refs can then be assigned to an element with ref-attribute. Following example shows a component that will focus to the text input when rendered.\n\n```js\nclass AutoFocusTextInput extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.textInput = React.createRef()\n  }\n  componentDidMount() {\n    this.textInput.current.focus()\n  }\n  render() {\n    return \u003cinput ref={this.textInput} /\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why are string refs considered legacy in React?\n\n\u003e Although string refs are not deprecated, they are considered legacy, and will likely be deprecated at some point in the future. Callback refs are preferred.\n\n**Callback Refs:**\n\nInstead of passing a **ref** attribute created by `createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.\n\n**Example:**\n\n```js\n// Ref.js\n\nclass CustomTextInput extends React.Component {\n  constructor(props) {\n    super(props);\n    this.textInput = null;\n\n    this.setTextInputRef = (element) =\u003e {\n      this.textInput = element;\n    };\n  }\n\n  handleSubmit = (e) =\u003e {\n    e.preventDefault();\n    console.log(this.textInput.value);\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cform onSubmit={(e) =\u003e this.handleSubmit(e)}\u003e\n          \u003cinput type=\"text\" ref={this.setTextInputRef} /\u003e\n          \u003cbutton\u003eSubmit\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n```js\n// App.js\n\nconst App = () =\u003e (\n  \u003cdiv style={styles}\u003e\n    \u003cHello name=\"React Refs\" /\u003e\n    \u003cCustomText /\u003e\n  \u003c/div\u003e\n)\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-refs-hiw59?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is `forwardRef()` in React?\n\nRef forwarding is a technique for passing a `ref` through a component to one of its children. It is very useful for cases like reusable component libraries and Higher Order Components (HOC).\n\nWe can forward a `ref` to a component by using the `React.forwardRef()` function. Ref forwarding allows components to take a ref they receive and pass it further down (in other words, \"forward\" it) to a child.\n\n**Example:**\n\n```js\n// Ref.js\nconst TextInput = React.forwardRef((props, ref) =\u003e (\n  \u003cinput type=\"text\" placeholder=\"Hello World\" ref={ref} /\u003e\n))\n\nconst inputRef = React.createRef()\n\nclass CustomTextInput extends React.Component {\n  handleSubmit = e =\u003e {\n    e.preventDefault()\n    console.log(inputRef.current.value)\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cform onSubmit={e =\u003e this.handleSubmit(e)}\u003e\n          \u003cTextInput ref={inputRef} /\u003e\n          \u003cbutton\u003eSubmit\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\nIn the example above, we have a component called TextInput that has a child which is an input field. First, we start by creating a ref with the line of code below:\n\n```js\nconst inputRef = React.createRef()\n```\n\nWe pass our ref down to `\u003cTextInput ref={inputRef}\u003e` by specifying it as a JSX attribute. React then forwards the `ref` to the `forwardRef()` function as a second argument. Next, We forward this `ref` argument down to `\u003cinput ref={ref}\u003e`. The value of the DOM node can now be accessed at `inputRef.current`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to debug forwardRefs() in DevTools?\n\n**React.forwardRef** accepts a render function as parameter and DevTools uses this function to determine what to display for the ref forwarding component.\n\n**Problem:** If you don\\'t name the render function or not using displayName property then it will appear as \"ForwardRef\" in the DevTools,\n\n```js\nconst WrappedComponent = React.forwardRef((props, ref) =\u003e {\n  return \u003cLogProps {...props} forwardedRef={ref} /\u003e;\n});\n```\n\n**Solution:** If you name the render function then it will appear as \"ForwardRef(myFunction)\"\n\n```js\nconst WrappedComponent = React.forwardRef(function myFunction(props, ref) {\n  return \u003cLogProps {...props} forwardedRef={ref} /\u003e;\n});\n```\n\n**Example:**\n\n```js\nconst ForwardP = React.forwardRef(function ForwardP(props, ref) {\n  return (\n    \u003c\u003e\n      \u003cp\u003eI'm a real component too\u003c/p\u003e\n      \u003cp\u003e\n        Especially with \u003ccode\u003euseImperativeMethods\u003c/code\u003e\n      \u003c/p\u003e\n      \u003cp {...props} ref={ref} /\u003e\n    \u003c/\u003e\n  );\n});\n\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cForwardP style={{ opacity: 0.5 }}\u003e\n        But my props are \u003ccode\u003enull\u003c/code\u003e in DevTools\n      \u003c/ForwardP\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/forwardRef.png\" alt=\"forwardRef()\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-forwardref-ccqgu?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between useRef() and useState() in React?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 16. REACT COMPOSITION\n\n\u003cbr/\u003e\n\n## Q. Explain Inheritance in React?\n\nInheritance uses the keyword **extends** to allow any component to use the properties and methods of another component connected with the parent. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or derived class.\n\nUsing the **extends** keyword, it allows the current component to access all the component\\'s properties, including the function, and trigger it from the child component.\n\n**Example:**\n\n```js\nimport React from \"react\";\n\n/**\n * Parent Class\n */\nexport class ParentClass extends React.Component {\n  constructor(props) {\n    super(props);\n    this.callMe = this.callMe.bind(this);\n  }\n\n  // ParentClass function\n  callMe() {\n    console.log(\"This is a method from parent class\");\n  }\n\n  render() {\n    return false;\n  }\n}\n\n/**\n * Child Class\n */\nexport default class App extends ParentClass {\n  render() {\n    return \u003cbutton onClick={() =\u003e this.callMe()}\u003eCall Parent\u003c/button\u003e;\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-inheritance-c6uc64?file=/src/App.js)**\n\n*Note: React does not use inheritance except in the initial component class, which extends from the **react** package.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Composition in React?\n\nComposition is also a familiar concept in Object Oriented Programming. Instead of inheriting properties from a base class, it describes a class that can reference one or more objects of another class as instances.\n\n**Example:**\n\n```js\n/**\n * Composition in React\n */\nimport React, { useState } from \"react\";\nimport Name from \"./Name\";\n\nexport default function App() {\n  const [name, setName] = useState(\"\");\n\n  return (\n    \u003cform\u003e\n      \u003ch2\u003eReact Composition Example\u003c/h2\u003e\n      \u003cName name={name} setName={setName} /\u003e\n      \u003ch3\u003e{name}\u003c/h3\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n```js\n/**\n * Name Component\n * @param {*} param0 - name\n * @param {*} param1 - setName\n */\nexport default function Name({ name, setName }) {\n  return (\n    \u003cdiv\u003e\n      \u003clabel\u003eName: \u003c/label\u003e\n      \u003cinput value={name} onChange={(event) =\u003e setName(event.target.value)} /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-composition-kq6fpc?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Composition is different from Inheritance in React?\n\nInheritance used the `is-a` relationship method. Derived components had to inherit the properties of the base component and it was quite complicated while modifying the behavior of any component.\n\nComposition does not inherit properties, only the behavior. In inheritance, it was difficult to add new behavior because the derived component was inheriting all the properties of parent class and it was quite difficult to add new behavior. But in composition, we only inherit behavior and adding new behavior is fairly simple and easy.\n\nReact recommends use of Composition over Inheritance, here is why. Everything in React is a component, and it follows a strong component based model. This is one of the primary reasons that composition is a better approach than inheritance for code reuse.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 17. REACT CSS STYLING\n\n\u003cbr/\u003e\n\n## Q. How to use styles in React.js?\n\nReact Components can add styling in the following ways:\n\n**1. Inline Styling:**\n\nIn JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces `{{}}`. Since the inline CSS is written in a JavaScript object, properties with two names, like `background-color`, must be written with camel case syntax:\n\n**Example:**\n\n```js\n/**\n * Inline Styling\n */\nclass HeaderComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1 style={{backgroundColor: \"lightblue\"}}\u003eHeader Component Style!\u003c/h1\u003e\n        \u003cp\u003eAdd a little style!\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/BaRJmyG?editors=0010)**\n\n**2. JavaScript Object:**\n\nWe can also create an object with styling information, and refer to it in the style attribute:\n\n**Example:**\n\n```js\n/**\n * JavaScript Object\n */\nclass HeaderComponent extends React.Component {\n  render() {\n    const mystyle = {\n      color: \"white\",\n      backgroundColor: \"DodgerBlue\",\n      padding: \"10px\",\n      fontFamily: \"Arial\"\n    };\n    return (\n      \u003cdiv\u003e\n        \u003ch1 style={mystyle}\u003eHeader Component Style!\u003c/h1\u003e\n        \u003cp\u003eAdd a little style!\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/abWEVvp?editors=0010)**\n\n**3. CSS Stylesheet:**\n\nYou can write your CSS styling in a separate file, just save the file with the .css file extension, and import it in your application.\n\n**Example:**\n\n```css\n/**  \n * App.css \n */\nbody {\n  background-color: #282c34;\n  color: white;\n  padding: 40px;\n  font-family: Arial;\n  text-align: center;\n}\n```\n\n```js\n/**\n * CSS Stylesheet\n */\nimport './App.css';\n\nclass HeaderComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eHeader Component Style!\u003c/h1\u003e\n        \u003cp\u003eAdd a little style!.\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n**4. CSS Modules:**\n\nCSS Modules are convenient for components that are placed in separate files\n\n**Example:**\n\n```css\n/**\n * mystyle.module.css\n */\n.bigblue {\n  color: DodgerBlue;\n  padding: 40px;\n  font-family: Arial;\n  text-align: center;\n}\n```\n\n```js\n/**\n * CSS Modules\n */\nimport styles from './mystyle.module.css'; \n\nclass HeaderComponent extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1 className={styles.bigblue}\u003eHeader Component Style!\u003c/h1\u003e\n        \u003cp\u003eAdd a little style!.\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to conditionally apply CSS classes in React JS?\n\n**Example:** Using the ternary operator\n\n```js\nclass App extends Component {\n  constructor() {\n    super()\n    this.state = { isRed: true }\n  }\n\n  render() {\n    const isRed = this.state.isRed\n\n    return \u003cp style={{ color: isRed ? 'red' : 'blue' }}\u003eExample Text\u003c/p\u003e\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/BaRJGre?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to combine multiple inline style objects?\n\n**Using Spread operator:**\n\n```js\nconst box = {\n    color: \"green\",\n    fontSize: '23px'\n}\n\nconst shadow = {\n    background: \"orange\",\n    boxShadow: \"1px 1px 1px 1px #cccd\"\n}\n\nexport default function App(){\n    return (\n      \u003cdiv style={{...box, ...shadow}}\u003e\n         \u003ch1\u003eHello React\u003c/h1\u003e\n      \u003c/div\u003e\n    )\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codepen.io/learning-zone/pen/RwVxqdv?editors=0010)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the popular package for animation in React JS?\n\n* [React Transition Group](https://reactcommunity.org/react-transition-group/)\n* [React Spring](https://react-spring.io/)\n* [Framer Motion](https://www.framer.com/motion/)\n* [React Motion](https://github.com/chenglou/react-motion)\n* [React Move](https://react-move.js.org/#/getting-started/features)\n* [React Animations](https://github.com/FormidableLabs/react-animations)\n* [React Reveal](https://www.react-reveal.com/)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the benefit of styles modules?\n\nCSS module is a CSS file in which all class names and animation names are scoped locally by default. In the React application, we usually create a single `.css` file and import it to the main file so the CSS will be applied to all the components.\n\nBut using CSS modules helps to create separate CSS files for each component and is local to that particular file and avoids class name collision.\n\n**Benefits of CSS modules:**\n\n* Using CSS modules avoid namespace collision for CSS classes\n* You can use the same CSS class in multiple CSS files\n* You can confidently update any CSS file without worrying about affecting other pages\n* Using CSS Modules generates random CSS classes when displayed in the browser\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are styled components?\n\nThe `Styled-components` is a CSS-in-JS styling framework that uses tagged template literals in JavaScript and the power of CSS to provide a platform that allows you to write actual CSS to style React components.\n\nThe `styled-components` comes with a collection of helper methods, each corresponding to a DOM node for example `\u003ch1\u003e`, `\u003cheader\u003e`, `\u003cbutton\u003e`, and SVG elements like `line` and `path`. The helper methods are called with a chunk of CSS, using an obscure JavaScript feature known as “tagged template literals”.\n\n**Example:**\n\n```js\nimport styled from 'styled-components'\n\nconst Button = styled.button`\n  color: black;\n  //...\n`\n\nconst WhiteButton = Button.extend`\n  color: white;\n  //...\n`\n\nrender(\n  \u003cdiv\u003e\n    \u003cButton\u003eA black button, like all buttons\u003c/Button\u003e\n    \u003cWhiteButton\u003eA white button\u003c/WhiteButton\u003e\n  \u003c/div\u003e\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use useSpring() for animation?\n\nReact Spring is a spring-physics based animation library that powers most UI related animation in React. It is a bridge on the two existing React animation libraries; `React Motion` and `Animated`. It inherits animated powerful interpolations and performance while maintaining react-motion\\'s ease of use.\n\nThere are 5 hooks in react-spring currently:\n\n* **useSpring** a single spring, moves data from a -\u003e b\n* **useSprings** multiple springs, for lists, where each spring moves data from a -\u003e b\n* **useTrail** multiple springs with a single dataset, one spring follows or trails behind the other\n* **useTransition** for mount/unmount transitions (lists where items are added/removed/updated)\n* **useChain** to queue or chain multiple animations together\n\n**1. useSpring():**\n\nIt turns defined values into animated values. It does this in two ways, either by overwriting the existing props with a different set of props on component re-render or by passing an updater function that returns a different set of props that is then used to update the props using set.\n\n**Example:**\n\n```js\n/**\n * useSpring()\n */\nimport React from \"react\";\nimport \"./styles.css\";\nimport { useSpring, animated } from \"react-spring\";\n\nexport default function App() {\n  const [message, setMessage] = React.useState(false);\n  const contentProps = useSpring({\n    opacity: message ? 1 : 0,\n    marginTop: message ? 0 : -500\n  });\n  return (\n    \u003cdiv className=\"container\"\u003e\n      \u003cdiv className=\"button-container\"\u003e\n        \u003cbutton onClick={() =\u003e setMessage((a) =\u003e !a)} className=\"button\"\u003e\n          Click Here\n        \u003c/button\u003e\n      \u003c/div\u003e\n\n      \u003canimated.div className=\"box\" style={contentProps}\u003e\n        \u003ch1\u003eReact Spring\u003c/h1\u003e\n      \u003c/animated.div\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usespring-rkhstc?file=/src/App.js)**\n\n**2. useSpring():**\n\nIt works kind of like a mix between useSpring() and useTransition() in that it takes an array, maps over it, and uses the from and to properties to assign the animation. For our styles we can just pass in the values from each item in our array.\n\n**Example:**\n\n```js\n/**\n * useSprings()\n */\nimport React, { useState } from \"react\";\nimport { animated, useSprings } from \"react-spring\";\n\nexport default function App() {\n  const [on, toggle] = useState(false);\n\n  const items = [\n    { color: \"red\", opacity: 1 },\n    { color: \"blue\", opacity: 0.6 },\n    { color: \"green\", opacity: 0.2 }\n  ];\n\n  const springs = useSprings(\n    items.length,\n    items.map((item) =\u003e ({\n      from: { color: \"#fff\", opacity: 0 },\n      to: {\n        color: on ? item.color : \"#fff\",\n        opacity: on ? item.opacity : 0\n      }\n    }))\n  );\n\n  return (\n    \u003cdiv\u003e\n      {springs.map((animation) =\u003e (\n        \u003canimated.h1 style={animation}\u003eHello World\u003c/animated.h1\u003e\n      ))}\n      \u003cbutton onClick={() =\u003e toggle(!on)}\u003eClick Here\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usespring-rkhstc?file=/src/App.js)**\n\n**3. useTrail():**\n\nIt allows to create an effect similar to both useSpring() and useSprings(), it will allow us to attach an animation to multiple items but instead of being executed at the same time, they will be executed one after the other. It just takes a number for how many we want and the style object.\n\n**Example:**\n\n```js\n/**\n * useTrail()\n */\nimport React, { useState } from \"react\";\nimport { animated, useTrail } from \"react-spring\";\n\nexport default function App() {\n  const [on, toggle] = useState(false);\n\n  const springs = useTrail(3, {\n    to: { opacity: on ? 1 : 0 },\n    config: { tension: 250 }\n  });\n\n  return (\n    \u003cdiv\u003e\n      {springs.map((animation, index) =\u003e (\n        \u003canimated.h1 style={animation} key={index}\u003e\n          Hello World\n        \u003c/animated.h1\u003e\n      ))}\n      \u003cbutton onClick={() =\u003e toggle(!on)}\u003eClick Here\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usetrail-jc3qc5?file=/src/App.js)**\n\n**4. useTransition():**\n\nIt allows to create an animated transition group. It takes in the elements of the list, their keys, and lifecycles. The animation is triggered on appearance and disappearance of the elements.\n\n**Example:**\n\n```js\nimport React, { useState } from 'react'\nimport { animated, useTransition } from 'react-spring'\n\nconst [on, toggle] = useState(false)\n\nconst transition = useTransition(on, null, {\n  from: { opacity: 0 },\n  enter: { opacity: 1 },\n  leave: { opacity: 0 }\n});\n\nreturn (\n\u003cdiv\u003e\n  {transition.map(({ item, key, props }) =\u003e (\n  item \u0026\u0026 \u003canimated.div style={props} \u003eHello world\u003c/animated.div\u003e\n  ))}\n\n  \u003cbutton onClick={() =\u003e toggle(!on)}\u003eChange\u003c/button\u003e\n\u003c/div\u003e\n)\n```\n\n**5. useChain():**\n\nIt allows to set the execution sequence of previously defined animation hooks. To do this, we use `refs`, which will subsequently prevent the independent execution of the animation.\n\n**Example:**\n\n```js\nimport React, { useState, useRef } from 'react'\nimport { animated, useSpring, useTrail, useChain} from 'react-spring'\n\n\nconst App = () =\u003e {\n  const [on, toggle] = useState(false)\n\n  const springRef = useRef()\n  const spring = useSpring({\n    ref: springRef,\n    from: { opacity: .5 },\n    to: { opacity: on ? 1 : .5 },\n    config: { tension: 250 }\n  })\n\n  const trailRef = useRef()\n  const trail = useTrail(5, {\n    ref: trailRef,\n    from: { fontSize: '10px' },\n    to: { fontSize: on ? '45px' : '10px' }\n  })\n\n  useChain(on ? [springRef, trailRef] : [trailRef, springRef])\n\n  return (\n    \u003cdiv\u003e\n      {trail.map((animation, index) =\u003e (\n        \u003canimated.h1 style={{ ...animation, ...spring }} key={index}\u003eHello World\u003c/animated.h1\u003e\n      ))}\n\n      \u003cbutton onClick={() =\u003e toggle(!on)}\u003eChange\u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usechain-ltxk82?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How many ways can we style the React Component?\n\n**1. CSS Stylesheet:**\n\n```css\n.DottedBox {\n  margin: 40px;\n  border: 5px dotted pink;\n}\n\n.DottedBox_content {\n  font-size: 15px;\n  text-align: center;\n}\n```\n\n```js\nimport React from 'react'\nimport './DottedBox.css'\n\nconst DottedBox = () =\u003e (\n  \u003cdiv className=\"DottedBox\"\u003e\n    \u003cp className=\"DottedBox_content\"\u003eGet started with CSS styling\u003c/p\u003e\n  \u003c/div\u003e\n)\n\nexport default DottedBox\n```\n\n**2. Inline styling:**\n\nIn React, inline styles are not specified as a string. Instead they are specified with an object whose **key** is the **camelCased** version of the style name, and whose value is the style\\'s value, usually a string.\n\n```js\nimport React from 'react'\n\nconst divStyle = {\n  margin: '40px',\n  border: '5px solid pink'\n}\nconst pStyle = {\n  fontSize: '15px',\n  textAlign: 'center'\n}\n\nconst Box = () =\u003e (\n  \u003cdiv style={divStyle}\u003e\n    \u003cp style={pStyle}\u003eGet started with inline style\u003c/p\u003e\n  \u003c/div\u003e\n)\n\nexport default Box\n```\n\n* We can create a variable that stores style properties and then pass it to the element like `style={nameOfvariable}`\n* We can also pass the styling directly `style={{color: 'pink'}}`\n\n**3. CSS Modules:**\n\nA CSS Module is a CSS file in which all class names and animation names are scoped locally by default.\n\n```css\n:local(.container) {\n   margin: 40px;\n   border: 5px dashed pink;\n }\n :local(.content) {\n   font-size: 15px;\n   text-align: center;\n }\n```\n\n```js\nimport React from 'react'\nimport styles from './DashedBox.css'\n\nconst DashedBox = () =\u003e (\n  \u003cdiv className={styles.container}\u003e\n    \u003cp className={styles.content}\u003eGet started with CSS Modules style\u003c/p\u003e\n  \u003c/div\u003e\n)\n\nexport default DashedBox\n```\n\nwe import css file `import styles './DashedBox.css'`, then we access to className as we access to object.\n\n* `:local(.className)`- this when you use create-react-app because of webpack configurations\n* `.className` - this if you use your own react boilerplate.\n\n**4. Styled-components:**\n\nStyled-components is a library for React and React Native that allows to use component-level styles in component application that are written with a mixture of JavaScript and CSS\n\n```bash\nnpm install styled-components --save\n```\n\n```js\nimport React from 'react'\nimport styled from 'styled-components'\n\nconst Div = styled.div`\n  margin: 40px;\n  border: 5px outset pink;\n  \u0026:hover {\n   background-color: yellow;\n }\n`;\n\nconst Paragraph = styled.p`\n  font-size: 15px;\n  text-align: center;\n`;\n\nconst OutsetBox = () =\u003e (\n  \u003cDiv\u003e\n    \u003cParagraph\u003eGet started with styled-components\u003c/Paragraph\u003e\n  \u003c/Div\u003e\n)\n\nexport default OutsetBox\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you apply vendor prefixes to inline styles in React?\n\nIn React, inline styles keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes other than `ms` should begin with a capital letter.\n\n```js\nconst divStyle = {\n  background: \"#eee\",\n  color: \"blue\",\n  padding: \"20px\",\n  margin: \"20px\",\n  WebkitTransition: \"all\", // note the capital 'W' here\n  msTransition: \"all\" // 'ms' is the only lowercase vendor prefix\n};\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-vendor-prefix-k29wi?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the popular animation package in React?\n\n**ReactCSSTransitionGroup:**\n\nReactCSSTransitionGroup is a high-level API based on ReactTransitionGroup and is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM. It has four components that display transitions from one component state to another using a declarative API used for mounting and unmounting of components:\n\n1. Transition\n2. CSSTransition\n3. SwitchTransition\n4. TransitionGroup\n\n**Example:**\n\n```js\nimport ReactCSSTransitionGroup from 'react-transition-group'\n\nclass AnimationComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {items: ['hello', 'world', 'click', 'me']}\n    this.handleAdd = this.handleAdd.bind(this)\n  }\n\n  handleAdd() {\n    const newItems = this.state.items.concat([\n      prompt('Enter some text')\n    ])\n    this.setState({items: newItems})\n  }\n\n  handleRemove(i) {\n    let newItems = this.state.items.slice()\n    newItems.splice(i, 1)\n    this.setState({items: newItems})\n  }\n\n  render() {\n    const items = this.state.items.map((item, i) =\u003e (\n      \u003cdiv key={item} onClick={() =\u003e this.handleRemove(i)}\u003e\n        {item}\n      \u003c/div\u003e\n    ))\n\n    return (\n      \u003cdiv\u003e\n        \u003cbutton onClick={this.handleAdd}\u003eAdd Item\u003c/button\u003e\n        \u003cReactCSSTransitionGroup\n          transitionName=\"example\"\n          transitionEnterTimeout={500}\n          transitionLeaveTimeout={300}\u003e\n          {items}\n        \u003c/ReactCSSTransitionGroup\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\nIn this component, when a new item is added to ReactCSSTransitionGroup it will get the `example-enter` CSS class and the `example-enter-active` CSS class added in the next tick. This is a convention based on the `transitionName` prop.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to display style based on props value?\n\n```js\nimport styled from 'styled-components'\n\nconst Button = styled.button`\n  background: ${props =\u003e props.primary ? 'palevioletred' : 'white'}\n  color: ${props =\u003e props.primary ? 'white' : 'palevioletred'}\n`;\n\nfunction MyPureComponent(props) {\n  return (\n    \u003cdiv\u003e\n      \u003cButton\u003eNormal\u003c/Button\u003e\n      \u003cButton primary\u003ePrimary\u003c/Button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 18. REACT INTERNATIONALIZATION\n\n\u003cbr/\u003e\n\n## Q. How to translate your React app with react-i18next?\n\n**Installing dependencies:**\n\n```bash\nnpm install react-i18next i18next i18next-browser-languagedetector --save\n```\n\n**Configure i18next:**\n\nCreate a new file `i18n.js` beside your `index.js` containing following content:\n\n```js\n/**\n * i18next Component\n */\nimport i18n from \"i18next\";\nimport LanguageDetector from \"i18next-browser-languagedetector\";\nimport { initReactI18next } from \"react-i18next\";\n\ni18n\n  .use(LanguageDetector)\n  .use(initReactI18next)\n  .init({\n    // we init with resources\n    resources: {\n      en: {\n        translations: {\n          \"Welcome to React\": \"Welcome to React and react-i18next\"\n        }\n      },\n      hi: {\n        translations: {\n          \"Welcome to React\": \"React और react-i18next में आपका स्वागत है\"\n        }\n      }\n    },\n    fallbackLng: \"en\",\n    debug: true,\n\n    // have a common namespace used around the full app\n    ns: [\"translations\"],\n    defaultNS: \"translations\",\n\n    keySeparator: false, // we use content as keys\n\n    interpolation: {\n      escapeValue: false\n    }\n  });\n\nexport default i18n;\n```\n\nWe pass the i18n instance to `react-i18next` which will make it available for all the components via the context api.\n\n```js\n/**\n * useTranslation() in React\n */\nimport React from \"react\";\nimport { useTranslation } from \"react-i18next\";\n\nexport default function App() {\n  const { t, i18n } = useTranslation();\n\n  const changeLanguage = (lng) =\u003e {\n    i18n.changeLanguage(lng);\n  };\n\n  return (\n    \u003c\u003e\n      \u003ch2\u003e{t(\"Welcome to React\")}\u003c/h2\u003e\n      \u003cbutton onClick={() =\u003e changeLanguage(\"en\")}\u003eEnglish\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e changeLanguage(\"hi\")}\u003eHindi\u003c/button\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-usetranslation-5gb2jx?file=/src/App.js)**\n\n**Reference:**\n\n* *[https://react.i18next.com/guides/quick-start](https://react.i18next.com/guides/quick-start)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 19. REACT TESTING\n\n\u003cbr/\u003e\n\n## Q. Why should we use Test-Driven Development (TDD) for ReactJS?\n\nTest-driven development is an approach when developers create a product backwards. TDD requires developers to write tests first and only then start to write the code. TDD is a development method that utilizes repetition of a short development cycle called Red-Green-Refactor.\n\n**Process:**\n\n1. Add a test\n1. Run all tests and see if the new test fails (red)\n1. Write the code to pass the test (green)\n1. Run all tests\n1. Refactor\n1. Repeat\n\n**Pros:**\n\n1. Design before implementation\n1. Helps prevent future regressions and bugs\n1. Increases confidence that the code works as expected\n\n**Cons:**\n\n1. Takes longer to develop (but it can save time in the long run)\n1. Testing edge cases is hard\n1. Mocking, faking, and stubbing are all even harder\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain react unit testing using Jest and Enzyme?\n\n**1. Jest:**\n\nJest is a JavaScript unit testing framework, used by Facebook to test services and React applications. Jest acts as a **test runner**, **assertion library**, and **mocking library**.\n\nJest also provides Snapshot testing, the ability to create a rendered *snapshot* of a component and compare it to a previously saved *snapshot*. The test will fail if the two do not match.\n\n**2. Enzyme:**\n\nEnzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components output. Enzyme, created by Airbnb, adds some great additional utility methods for rendering a component (or multiple components), finding elements, and interacting with elements.\n\n**Setup with Create React App:**\n\n```bash\n# Set up a React application\nnpx create-react-app counter-app\n\n# for rendering snapshots\nnpm install  react-test-renderer --save-dev\n\n# for dom testing\nnpm install enzyme --save-dev\n```\n\n```js\n/**\n * App.js\n */\nimport React, { useState } from \"react\";\n\nexport default function Counter() {\n  const [counter, setCounter] = useState(0);\n\n  const incrementCounter = () =\u003e {\n    setCounter((prevCounter) =\u003e prevCounter + 1);\n  };\n\n  return (\n    \u003c\u003e\n      \u003cbutton onClick={incrementCounter}\u003eClick Me\u003c/button\u003e\n      \u003ch2 data-testid=\"counter\"\u003e{counter}\u003c/h2\u003e\n    \u003c/\u003e\n  );\n}\n```\n\n**Writing Test Cases:**\n\n```js\n/**\n * App.test.js\n */\nimport React from \"react\";\nimport { shallow } from \"enzyme\";\nimport App from \"./App\";\n\n// Testing App Component\ndescribe(\"App component\", () =\u003e {\n  it(\"starts with a count of 0\", () =\u003e {\n    const wrapper = shallow(\u003cApp /\u003e);\n    const text = wrapper.find(\"h2\").text();\n    expect(text).toEqual(\"0\");\n  });\n});\n\n// Testing Button Event\ndescribe(\"App component\", () =\u003e {\n  it(\"increments count by 1 when the increment button is clicked\", () =\u003e {\n    const mockCallBack = jest.fn();\n\n    const button = shallow(\u003cbutton onClick={mockCallBack}\u003eClick Me\u003c/button\u003e);\n    button.find(\"button\").simulate(\"click\");\n    expect(mockCallBack.mock.calls.length).toEqual(1);\n  });\n});\n\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-test-qz363f?file=/src/App.test.js)**\n\n**Reference:**\n\n* *[https://jestjs.io/docs/en/tutorial-react](https://jestjs.io/docs/en/tutorial-react)*\n* *[https://enzymejs.github.io/enzyme/](https://enzymejs.github.io/enzyme/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain unit test structure in React?\n\n```js\ndescribe('Component Description', () =\u003e {\n  beforeAll(() =\u003e {\n    /* Runs before all tests */\n  })\n  afterAll(() =\u003e {\n    /* Runs after all tests */\n  })\n  beforeEach(() =\u003e {\n    /* Runs before each test */\n  })\n  afterEach(() =\u003e {\n    /* Runs after each test */\n  })\n\n  test('test case decription', () =\u003e {\n    const actual = fn(['one', 'Two', 'Three'])\n    expect(actual).toEqual(['1 =\u003e One', '2 =\u003e Two', '3 =\u003e Three'])\n  })\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the matchers available in jest framework?\n\n**1. Basic matchers:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toBe()    |expect(42).toBe(42)           | Strict equality (===)    |\n|not.toBe()|expect(42).not.toBe(3)        | Strict equality (!==)    |\n|toEqual() |expect({ a: undefined, b: 2 }).toEqual({ b: 2 }) |Deep equality|\n|not.toStrictEqual()|expect({ a: undefined, b: 2 }).not.toStrictEqual({ b: 2 })|Strict equality|\n\n**2. Truthiness:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toBeTruthy()|expect('foo').toBeTruthy()| Matches anything that an if statement treats as true (not false, 0, '', null, undefined, NaN)|\n|toBeFalsy()|expect('').toBeFalsy() |Matches anything that an if statement treats as false (false, 0, '', null, undefined, NaN)|\n|toBeNull()|expect(null).toBeNull()|Matches only null|\n|toBeUndefined()|expect(undefined).toBeUndefined()|Matches only undefined|\n|toBeDefined()|expect(7).toBeDefined()|The opposite of toBeUndefined|\n|toEqual()  |expect(true).toEqual(expect.any(Boolean)) |Matches true or false|\n|toBeInTheDocument()|expect(getByText(/React/i)).toBeInTheDocument()| Return true/false |\n\n**3. Numbers:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toBeGreaterThan()|expect(2).toBeGreaterThan(1)| |\n|toBeGreaterThanOrEqual()|expect(1).toBeGreaterThanOrEqual(1)| |\n|toBeLessThan() | expect(1).toBeLessThan(2)| |\n|toBeLessThanOrEqual()|expect(1).toBeLessThanOrEqual(1)| |\n|toBeCloseTo()|expect(0.2 + 0.1).toBeCloseTo(0.3, 5) | |\n|toEqual()    |expect(NaN).toEqual(expect.any(Number))| |\n\n**4. Strings:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toMatch() |expect('long string').toMatch('str')| |\n|toEqual() |expect('string').toEqual(expect.any(String))| |\n|toMatch() |expect('coffee').toMatch(/ff/) | |\n|not.toMatch()|expect('pizza').not.toMatch('coffee')| |\n|toEqual() | expect(['pizza', 'coffee']).toEqual([expect.stringContaining('zz'), expect.stringMatching(/ff/)])| |\n\n**5. Arrays:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toEqual() |expect([]).toEqual(expect.any(Array))|  |\n|toHaveLength()|expect(['Alice', 'Bob', 'Eve']).toHaveLength(3)| |\n|toContain() |expect(['Alice', 'Bob', 'Eve']).toContain('Alice')| |\n|toContainEqual()|expect([{ a: 1 }, { a: 2 }]).toContainEqual({ a: 1 })| |\n|toEqual() |expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(['Alice', 'Bob']))| |\n\n**6. Objects:**\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toHaveProperty()|expect({ a: 1 }).toHaveProperty('a')| |\n|toMatchObject()|expect({ a: 1, b: 2 }).toMatchObject({ a: 1 })| |\n\n**7. Exceptions:**\n\n```js\nconst fn = () =\u003e { throw new Error('Throw some custom error!') }\n```\n\n| Method   |Example                       | Description              |\n|----------|------------------------------|--------------------------|\n|toThrow() |expect(fn).toThrow()| |\n|toThrow() |expect(fn).toThrow('Out of cheese')| |\n|toThrowErrorMatchingSnapshot()|expect(fn).toThrowErrorMatchingSnapshot()| |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is TestRenderer package in React?\n\nThis package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.\n\nThis package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.\n\n**Example:**\n\n```js\nimport TestRenderer from 'react-test-renderer';\n\nfunction Link(props) {\n  return \u003ca href={props.page}\u003e{props.children}\u003c/a\u003e;\n}\n\nconst testRenderer = TestRenderer.create(\n  \u003cLink page=\"https://www.facebook.com/\"\u003eFacebook\u003c/Link\u003e\n);\n\nconsole.log(testRenderer.toJSON());\n// { type: 'a',\n//   props: { href: 'https://www.facebook.com/' },\n//   children: [ 'Facebook' ] }\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of the ReactTestUtils package?\n\n**ReactTestUtils** is used to test React-based components. It can simulate all the JavaScript-based events, which ReactJS supports. Some of its frequently methods are\n\n* `act()`\n* `mockComponent()`\n* `isElement()`\n* `isElementOfType()`\n* `isDOMComponent()`\n* `renderIntoDocument()`\n* `Simulate()`\n\n**act():**\n\nTo prepare a component for assertions, wrap the code rendering it and performing updates inside an act() call. This makes your test run closer to how React works in the browser.\n\n```js\nclass Counter extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {count: 0}\n    this.handleClick = this.handleClick.bind(this)\n  }\n  componentDidMount() {\n    document.title = `You clicked ${this.state.count} times`\n  }\n  componentDidUpdate() {\n    document.title = `You clicked ${this.state.count} times`\n  }\n  handleClick() {\n    this.setState(state =\u003e ({\n      count: state.count + 1,\n    }))\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cp\u003eYou clicked {this.state.count} times\u003c/p\u003e\n        \u003cbutton onClick={this.handleClick}\u003e\n          Click me\n        \u003c/button\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n```js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { act } from 'react-dom/test-utils'\nimport Counter from './Counter'\n\nlet container\n\nbeforeEach(() =\u003e {\n  container = document.createElement('div')\n  document.body.appendChild(container)\n})\n\nafterEach(() =\u003e {\n  document.body.removeChild(container)\n  container = null\n})\n\nit('can render and update a counter', () =\u003e {\n  // Test first render and componentDidMount\n  act(() =\u003e {\n    ReactDOM.render(\u003cCounter /\u003e, container)\n  })\n  const button = container.querySelector('button')\n  const label = container.querySelector('p')\n  expect(label.textContent).toBe('You clicked 0 times')\n  expect(document.title).toBe('You clicked 0 times')\n\n  // Test second render and componentDidUpdate\n  act(() =\u003e {\n    button.dispatchEvent(new MouseEvent('click', {bubbles: true}))\n  })\n  expect(label.textContent).toBe('You clicked 1 times')\n  expect(document.title).toBe('You clicked 1 times')\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is react-test-renderer package in React?\n\nThis package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.\n\nEssentially, this package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a React DOM or React Native component without using a browser or `jsdom`.\n\n**Example:**\n\n```js\nimport React from 'react'\nimport renderer from 'react-test-renderer'\nimport App from './app.js' // The component being tested\n\n/**\n * Snapshot tests are a useful when UI does not change frequently.\n *\n * A typical snapshot test case for a mobile app renders a UI component, takes a snapshot,\n * then compares it to a reference snapshot file stored alongside the test.\n */\ndescribe('APP Component', () =\u003e {\n\n    test('Matches the snapshot', () =\u003e {\n      const tree = renderer.create(\u003cApp /\u003e).toJSON()\n      expect(tree).toMatchSnapshot()\n    })\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the benefits of using data-test selector over className or Id selector in Jest?\n\nHTML structure and css classes tend to change due to design changes. Which will cause to re-write tests quite often. Also, if we are using css-modules we can not rely on class names. Because of that, React provides `data-test` attribute for selecting elements in jsx.\n\n```js\n// APP Component\nimport React from 'react'\nimport './App.scss'\n\nfunction App() {\n  return (\n    \u003cdiv data-testid='app-header'\u003e\n      Hello React\n    \u003c/div\u003e\n  )\n}\nexport default App\n```\n\n```js\nimport React from 'react'\nimport { cleanup, render, screen } from \"@testing-library/react\";\nimport App from './App'\nafterEach(cleanup);\n\ndescribe('APP Component', () =\u003e {\n\n  let wrapper\n  beforeEach(() =\u003e {\n    wrapper = render(\u003cHeader/\u003e)\n  })\n\n  test('should check for the title', () =\u003e {\n    expect(screen.getByText(/Hello React/i)).toBeInTheDocument();\n  })\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to write unit test for multiple fetch with Promise.all using jest?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 20. REACT MISCELLANEOUS\n\n\u003cbr/\u003e\n\n## Q. What is React.cloneElement?\n\nThe **React.cloneElement()** function returns a copy of a specified element. Additional props and children can be passed on in the function. This function is used when a parent component wants to add or modify the prop(s) of its children.\n\n```js\nReact.cloneElement(element, [props], [...children])\n```\n\nThe react.cloneElement() method accepts three arguments.\n\n* element: Element we want to clone.\n* props: props we need to pass to the cloned element.\n* children: we can also pass children to the cloned element (passing new children replaces the old children).\n\n**Example:**\n\n```js\nimport React from 'react'\n\nexport default class App extends React.Component {\n\n  // rendering the parent and child component\n  render() {\n    return (\n      \u003cParentComp\u003e\n        \u003cMyButton/\u003e\n        \u003cbr\u003e\u003c/br\u003e\n        \u003cMyButton/\u003e\n      \u003c/ParentComp\u003e\n    )\n  }\n}\n\n// The parent component\nclass ParentComp extends React.Component {\n  render() {\n    // The new prop to the added.\n    let newProp = 'red'\n      // Looping over the parent's entire children,\n      // cloning each child, adding a new prop.\n    return (\n      \u003cdiv\u003e\n        {React.Children.map(this.props.children,\n          child =\u003e {\n            return React.cloneElement(child,\n            {newProp}, null)\n        })}\n      \u003c/div\u003e\n    )\n  }\n}\n\n// The child component\nclass MyButton extends React.Component {\n  render() {\n    return \u003cbutton style =\n    {{ color: this.props.newProp }}\u003e\n    Hello World!\u003c/button\u003e\n  }\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-cloneelement-6mecw?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is render hijacking in React?\n\nThe phenomena of **render hijacking** is the ability to control what a component will output from another component. It actually means that, the users decorate their component by wrapping it into a Higher-Order component. By wrapping, they can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually allow hijacking, but by using HOC, users can make the component behave in a different way.\n\nIn Render Highjacking we can:\n\n* Read, add, edit, remove props in any of the React Elements outputted by render\n* Read, and modify the React Elements tree outputted by render\n* Conditionally display the elements tree\n* Wrapping the element\\'s tree for styling purposes.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is windowing technique in react?\n\n**Windowing** or **List virtualization** is a concept of only rendering or write the visible portion in the current \"window\" to the DOM. The number of items that rendered at first time are smaller than the original one. The remaining items are rendered when you scroll down to it. The DOM nodes of items that exit the window are replaced by the new ones. This improves the performance of rendering a large list.\n\n**[react-window](https://react-window.vercel.app/#/examples/list/fixed-size)** and **[react-virtualized](https://bvaughn.github.io/react-virtualized/#/components/List)** are popular windowing libraries. They provide several reusable components for displaying lists, grids, and tabular data.\n\n**Example:** react-window\n\n```js\nfunction renderRow(props) {\n  const { index, style } = props;\n\n  return (\n    \u003cListItem button style={style} key={index}\u003e\n      \u003cListItemText primary={`Item ${index + 1}`} /\u003e\n    \u003c/ListItem\u003e\n  );\n}\n\nexport default function VirtualizedList() {\n\n  return (\n    \u003cdiv\u003e\n      \u003cFixedSizeList height={400} width={200} itemSize={46} itemCount={100000}\u003e\n        {renderRow}\n      \u003c/FixedSizeList\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-window-rz5hf?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to optimize React Performance?\n\nReact uses many techniques to minimize the number of DOM operations for us already. For many applications, if you are using the production build, you may already meet or surpass your performance expectations. Nevertheless, there are several ways you can speed up your application.\n\n**1. React DevTools Profiler:**\n\nExperience performance problems with a specific component, the React DevTools Profiler is usually the first place to look.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/react-dev-tools.png\"  alt=\"React DevTools\" /\u003e\n\u003c/p\u003e\n\n**2. `shouldComponentUpdate()` method**\n\nReact provides a simple lifecycle method to indicate if a component needs re-rendering and that is, shouldComponentUpdate() which is triggered before the re-rendering process starts. The default implementation of this function returns **true**.\n\nIf you know that in some situations your component doesn\\'t need to update, you can return **false** from shouldComponentUpdate() instead, to skip the whole rendering process, including calling render() on component.\n\n```js\nshouldComponentUpdate(nextProps, nextState) {\n  return false;\n}\n```\n\n**3. Functional Components and PureComponent:**\n\nFunctional components reduce the bundle size as they are better at minifying than classes and they prevent construction of class instances.\n\nPure Components in React are the components which do not re-renders when the value of `state` and `props` has been updated with the same values. Pure Components restricts the re-rendering ensuring the higher performance of the Component.\n\n**4. React.memo():**\n\nReact.memo is a higher order component. It\\'s similar to `React.PureComponent` but for function components instead of classes.\n\n```js\nconst MyComponent = React.memo(function MyComponent(props) {\n  /* render using props */\n})\n```\n\nIf your function component renders the same result given the same props, you can wrap it in a call to `React.memo` for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.\n\n`React.memo` only checks for `prop` changes. If your function component wrapped in `React.memo` has a `useState` or `useContext` Hook in its implementation, it will still rerender when `state` or `context` change.\n\n**5. Virtualizing Long Lists:**\n\nIn order to address the issue with our long chat feed, the React team recommends a technique called windowing. This technique only renders the portion of the list that is visible to the user (+/- a given offset) in order to reduce the time to render. As the user scrolls, new list items are retrieved and rendered. `react-window` and `react-virtualized` are two libraries that provide components to help with list virtualization.\n\n**6. Use the Production Build:**\n\nReact\\'s production build improves react apps performance. The file size of the production build is significantly smaller, which means that the page loads faster as the browser has to download, parse, and execute fewer elements.\n\n**Reference:**\n\n* *[https://reactjs.org/docs/optimizing-performance.html](https://reactjs.org/docs/optimizing-performance.html)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do you understand with the term polling in React?\n\nThe **setInterval()** inside React components allows us to execute a function or some code at specific intervals. This will schedule once the React component mounts for the first time. To properly clear the interval, we return `clearInterval()` from the `useEffect()` Hook, passing in the interval.\n\n**Example:**\n\n```js\n/**\n * Polling in React\n */\nimport React, { useState, useEffect } from \"react\";\n\nexport default function App() {\n  const [seconds, setSeconds] = useState(0);\n\n  useEffect(() =\u003e {\n    const interval = setInterval(() =\u003e {\n      setSeconds((seconds) =\u003e seconds + 1);\n    }, 1000);\n    return () =\u003e clearInterval(interval);\n  }, []);\n\n  return \u003ch2\u003e{seconds} seconds have elapsed since mounting.\u003c/h2\u003e;\n}\n```\n\nThe example above shows a React component, IntervalExample, scheduling a new interval once it mounts to the DOM. The interval increments the seconds state value by one, every second.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/polling-in-react-obsl1k?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the drawbacks of MVW pattern?\n\nMVW stands for **Model-View-Whatever**\n\n* `MVC` - Model-View-Controller\n* `MVP` - Model-View-Presenter\n* `MVVM` - Model-View-ViewModel\n* `MVW / MV* / MVx` - Model-View-Whatever\n* `HMVC` - Hierarchical Model-View-Controller\n* `MMV` - Multiuse Model View\n* `MVA` - Model-View-Adapter\n\nMVW is easy to manage in a simple application, with few models/controllers. But we can easily start to witness problems as we grow in size with the following problems:\n\n1. There is need when models/controllers communicate with each others (through a service layer probably), and these modules changes the states of each others, and the more controllers, the more easy to lose control of who changed the state of a controller.\n2. Asynchronous network calls to retrieve data add uncertainty of when the model will be changed or modified, and imagine the user changing the UI while a callback from asynchronous call comeback, then we will have \"nondeterministic\" status of the UI.\n3. Change state/model has another layer of complexity which is the mutation. When to consider the state or model is changed and how to build tools to help recognize the mutation.\n4. Adding to that if the application is a collaborative applications, (like google docs for examples) where lots of data changes happening in real-time.\n5. No way to do undo (travel back in time) easily without adding so much extra code.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you update render elements?\n\nReact Elements are immutable i.e. once an element is created it is impossible to update its children or attribute. Thus, in order to update an element, we must use the `render()` method several times to update the value over time.\n\n**Example:**\n\n```js\nfunction showTime() {\n  const element = (\n    \u003cdiv\u003e\n      \u003ch2\u003eCurrent Time is: {new Date().toLocaleTimeString()}\u003c/h2\u003e\n    \u003c/div\u003e\n  );\n  ReactDOM.render(element, document.getElementById(\"root\"));\n}\n\nsetInterval(showTime, 1000);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-clock-1f5xp?file=/src/index.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between rendering and mounting in ReactJS?\n\n**Rendering** is any time a function component gets called (or a class-based render method gets called) which returns a set of instructions for creating DOM. `render()` function will be invoked every time rerendering happens in the component. It may happen either through a `state` change or a `prop` change.\n\n**Mounting** is when React `renders` the component for the first time and actually builds the initial DOM from those instructions. Mounting a react component means the actual addition of the DOM elements created by the react component into the browser DOM for the first time.\n\nA **re-render** is when React calls the function component again to get a new set of instructions on an already mounted component.\n\n**Example:**\n\n```js\n/**\n * React Render()\n */\nimport React from \"react\";\n\n/**\n * Message Component\n * @param {*} props\n */\nfunction Message(props) {\n  return \u003ch2\u003e{props.name}\u003c/h2\u003e;\n}\n\n/**\n * App Component\n */\nexport default class App extends React.Component {\n  state = {\n    showMessage: false\n  };\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cbutton onClick={() =\u003e this.setState({ showMessage: true })}\u003e Show Message \u003c/button\u003e\n        \u003cbutton onClick={() =\u003e this.setState({ showMessage: false })}\u003e Hide Message \u003c/button\u003e\n        {this.state.showMessage \u0026\u0026 \u003cMessage name=\"Hello React!\" /\u003e}\n      \u003c/div\u003e\n    );\n  }\n}\n```\n\nInternally, React will create an instance of `App` and will eventually call the `render()` method to get the first set of instructions for what it needs to build in the DOM. Anytime React calls the render method of a class-based component, we call that a **render**.\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-render-mh521n?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Flow in react?\n\n**Type Checking:**\n\nType checking means ensuring that the type of a property (variable, object, function, string) in a programming language is being used as it should be. It is the process of verifying and enforcing the constraints of types, and it can occur either at compile time or at runtime. It helps to detect and report errors.\n\nType checking can be divided into two: static type checking and dynamic type checking.\n\n**1. Static Type Checking:**\n\nStatic type checking is used in static-typed languages where the type of the variable is known at the compile time. This means that the type of the variable must be declared beforehand. Static typing usually results in compiled code that executes more quickly because the compiler already knows the exact data types that are in use.\n\n**2. Dynamic type checking:**\n\nDynamic type checking is used in dynamic-typed languages where the type is usually known at runtime. This means that the type of the variable doesn\\'t need to be explicitly defined.\n\n**Flow:**\n\nFlow is a static type checker for JavaScript apps that aims to find and eliminate problems as you code. Designed by the Facebook team for JavaScript developers, it\\'s a static type checker that catches common errors in your application before they run.\n\n**Integrating Flow:**\n\n```bash\n# Create React App with Flowchecker\nnpx create-react-app flowchecker\n\n# Add Dependency\nnpm install --save-dev flow-bin\n```\n\nThe next thing to do is add Flow to the \"scripts\" section of your package.json so that Flow can be used in the terminal. In the package.json file, add the code snippet below.\n\n```json\n \"scripts\": {\n      \"flow\": \"flow\",\n    }\n```\n\nFinally, for the Flow setup, run any of the commands below:\n\n```bash\nnpm run flow init\n```\n\nThis will help to create a Flow configuration file that should be committed. The Flow config file helps to determine the files that Flow should work with and what should be ignored.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the recommended way for static type checking?\n\nStatic type checkers like `Flow` and `TypeScript` identify certain types of problems before you even run your code. They can also improve developer workflow by adding features like auto-completion. For this reason, we should use `Flow` or `TypeScript` instead of `PropTypes` for larger code bases.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Flow and PropTypes?\n\n`Flow` is a static analysis tool which uses a superset of the language, allows to add type annotations to all of your code and catch an entire class of bugs at compile time.\n\n`PropTypes` is a basic type checker which has been patched onto React. It can't check anything other than the types of the props being passed to a given component.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is React Fiber?\n\nReact Fiber is the new **reconciliation algorithm**. Reconciliation is the process of comparing or diffing old trees with a new tree in order to find what is changed or modified. In the original reconciliation algorithm (now called **Stack Reconciler**), the processing of component trees was done synchronously in a single pass, so the main thread was not available for other UI related tasks like animation, layouts, and gesture handling. Fiber Reconciler has different goals:\n\n* Ability to split interruptible work in chunks.\n* Ability to prioritize, rebase, and reuse work in progress.\n* Ability to yield back and forth between parents and children to support layout in React.\n* Ability to return multiple elements from `render()`.\n\nA fiber is a JavaScript object that contains information about a component, its input, and output. At any time, a component instance has at most two fibers that correspond to it: the current fiber and the work-in-progress fiber. A fiber can be defined as a unit of work.\n\nReact Fiber performs reconciliation in two phases: Render and Commit\n\n**1. Lifecycle methods called during render phase:**\n\n* `UNSAFE_componentWillMount()`\n* `UNSAFE_componentWillReceiveProps()`\n* `getDerivedStateFromProps()`\n* `shouldComponentUpdate()`\n* `UNSAFE_componentWillUpdate()`\n* `render()`\n\n**2. Lifecycle methods called during commit phase:**\n\n* `getSnapshotBeforeUpdate()`\n* `componentDidMount()`\n* `componentDidUpdate()`\n* `componentWillUnmount()`\n\nThe earlier whole reconciliation process was synchronous (recursive), but in Fiber, it is divided into two phases. Render phase (a.k.a. Reconciliation phase) is asynchronous, so three of the lifecycle methods were marked unsafe because putting the code with side-effects inside these methods can cause problems, as lifecycle methods of different components are not guaranteed to fire in a predictable order.\n\nReact Fiber uses `requestIdleCallback()` to schedule the low priority work and `requestAnimationFrame()` to schedule high priority work.\n\n**Problems with Current Implementation:**\n\n* Long-running tasks cause frame drops.\n* Different tasks have different priorities.\n\n**How React Fiber works:**\n\n* It makes apps more fluid and responsible.\n* In the future, it could parallelize work a.k.a. Time Slicing.\n* It would improve startup time while rendering components using React Suspense.\n\nFiber is currently available for use but it runs in compatibility mode with the current implementation.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Does the static object work with ES6 classes in React?\n\nAlthough statics only works for `React.createClass()`, you can still write static methods in ES6 notation. If you are using ES7, then you can also write static properties.\n\n```js\nclass Component extends React.Component {\n    static propTypes = {\n    ...\n    }\n\n    static someMethod(){\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you access imperative API of web components?\n\nWeb Components often expose an imperative API to implement its functions. To access the imperative APIs of a web component, you will need to attach a **ref** to the component and interact with the DOM node directly. If you are using third-party web components, the recommended solution is to write a React component that behaves as a **wrapper** for your web component.\n\n**Example:** Using React in your Web Components\n\n```js\nvar proto = Object.create(HTMLElement.prototype, {\n  createdCallback: {\n    value: function() {\n      var mountPoint = document.createElement('span');\n      this.createShadowRoot().appendChild(mountPoint);\n\n      var name = this.getAttribute('name');\n      var url = 'https://www.google.com/search?q=' + encodeURIComponent(name);\n      ReactDOM.render(\u003ca href={url}\u003e{name}\u003c/a\u003e, mountPoint);\n    }\n  }\n});\ndocument.registerElement('x-search', {prototype: proto});\n```\n\n```js\nclass SearchComponent extends React.Component {\n  render() {\n    return \u003cdiv\u003eResults: \u003cx-search\u003e{this.props.name}\u003c/x-search\u003e!\u003c/div\u003e;\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of eslint plugin for hooks?\n\nThe ESLint plugin ( **eslint-plugin-react-hooks** ) enforces rules of Hooks to avoid bugs. It assumes that any function starting with \"use\" and a capital letter right after it is a Hook. In particular, the rule enforces that,\n\n* Calls to Hooks are either inside a PascalCase function (assumed to be a component) or another useSomething function (assumed to be a custom Hook).\n* Hooks are called in the same order on every render.\n\n```js\n// ESLint configuration\n{\n  \"plugins\": [\n    // ...\n    \"react-hooks\"\n  ],\n  \"rules\": {\n    // ...\n    \"react-hooks/rules-of-hooks\": \"error\", // Checks rules of Hooks\n    \"react-hooks/exhaustive-deps\": \"warn\" // Checks effect dependencies\n  }\n}\n```\n\n*Note: This plugin is included by default in Create React App.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is service worker in React.js?\n\nA service worker is a background worker that acts as a programmable proxy, allowing us to control what happens on a request-by-request basis. We can use it to make (parts of, or even entire) React apps work offline.\n\nService workers depend on two APIs to work effectively: `Fetch` (a standard way to retrieve content from the network) and `Cache` (content storage for application data. This cache is independent from the browser cache or network status).\n\n**Service Worker Lifecycle:**\n\nEach service worker goes through three steps in its lifecycle: registration, installation and activation.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/service-worker.png\" alt=\"Service Worker Lifecycle\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**Registration:**\n\nTo install a service worker, you need to register it in script. Registration informs the browser where your service worker is located and lets it know it can start installing in the background.\n\n**Example:** Basic registration in your `index.html` could look like this\n\n```js\n// Check for browser support of service worker\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker.register('service-worker.js')\n\n .then(function(registration) {\n   // Successful registration\n   console.log('Registration successful, scope is:', registration.scope);\n\n }).catch(function(err) {\n   // Failed registration, service worker won\\'t be installed\n   console.log('Service worker registration failed, error:', error);\n\n });\n}\n```\n\n**Installation and activation:**\n\nService workers are event driven. The installation and activation processes fire off corresponding **install** and **activate** events to which the service workers can respond.\n\nWith the service worker registered, the first time a user hits your PWA, the install event will be triggered and this is where you\\'ll want to cache the static assets for the page. \n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of registerServiceWorker in React?\n\nReact creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on slow network, user can still see results on the screen.\n\n**Example:** Enable service worker in react\n\n```js\n// index.js\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\nimport registerServiceWorker from './registerServiceWorker';\n\nReactDOM.render(\u003cApp /\u003e, document.getElementById('root'));\nregisterServiceWorker();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Virtual-DOM is more efficient than Dirty checking?\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/virtualdom-vs-realdom.png\" alt=\"Virtual DOM\" with=\"500px\" /\u003e\n\u003c/p\u003e\n\n**React Virtual DOM:**  \n\nIn React, Each time the DOM updates or data of page changes, a new Virtual DOM representation of the user interface is made. It is just a lightweight copy or DOM.\n\nVirtual DOM in React has almost same properties like a real DOM, but it can not directly change the content on the page. Working with Virtual DOM is faster as it does not update anything on the screen at the same time. In a simple way, Working with Virtual DOM is like working with a copy of real DOM nothing more than that.\n\nUpdating virtual DOM in ReactJS is faster because ReactJS uses\n\n1. It is efficient diff algorithm.\n1. It batched update operations\n1. It efficient update of sub tree only\n1. It uses observable instead of dirty checking to detect change\n\n**How Virtual DOM works in React:**  \n\nWhen we render a JSX element, each virtual DOM updates. This approach updates everything very quickly. Once the Virtual DOM updates, React matches the virtual DOM with a virtual DOM copy that was taken just before the update. By Matching the new virtual DOM with pre-updated version, React calculates exactly which virtual DOM has changed. This entire process is called **diffing**.\n\nWhen React knows which virtual DOM has changed, then React updated those objects. and only those object, in the real DOM. React only updates the necessary parts of the DOM. React\\'s reputation for performance comes largely from this innovation.\n\nIn brief, here is what happens when we update the DOM in React:\n\n1. The entire virtual DOM gets updated.\n1. The virtual DOM gets compared to what it looked like before you updated it. React matches out which objects have changed.\n1. The changed objects and the changed objects only get updated on the real DOM.\n1. Changes on the real DOM cause the screen to change finally.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between DOM and virtual DOM?\n\n**1. DOM:**\n\nDOM stands for \"Document Object Model\". The HTML DOM provides an interface (API) to traverse and modify the nodes. It contains methods like `getElementById()` or `removeChild()`.\n\nThe DOM is represented as a tree data structure. Because of that, the changes and updates to the DOM are fast. But after the change, the updated element and it\\'s children have to be re-rendered to update the application UI. The re-rendering or re-painting of the UI is what makes it slow.\n\n**2. Virtual DOM:**  \n\nThe virtual DOM is only a virtual representation of the DOM. Everytime the state of our application changes, the virtual DOM gets updated instead of the real DOM.\n\nThe Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction.\n\n**Why Virtual DOM is faster:**\n\nWhen new elements are added to the UI, a virtual DOM, which is represented as a tree is created. Each element is a node on this tree. If the state of any of these elements changes, a new virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual DOM tree.\n\nOnce this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM.\n\n**Pros of Virtual DOM:**  \n\n* Updates process is optimized and accelerated.\n* JSX makes components/blocks code readable.\n* React data binding establishes conditions for creation dynamic applications.\n* Virtual DOM is ideal for mobile first applications.\n* Prompt rendering. Using comprises methods to minimize number of DOM operations helps to optimize updating process and accelerate it.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/dom.png\" alt=\"Real DOM and Virtual DOM\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain DOM diffing?\n\nOnce the Virtual DOM is created, React compares this new representation with a snapshot of the previous version of the virtual DOM to see exactly which elements have changed.\n\nOnce the difference is known, React updates only those objects that differ on the actual DOM and the browser re-paints the screen. The next time state or props changes for a component in the application, a new virtual DOM tree of React elements will be created and the process will repeat.\n\nThe process of checking the difference between the new Virtual DOM tree and the old Virtual DOM tree is called **diffing**. Diffing is accomplished by a **heuristic O(n)** algorithm. During this process, React will deduce the minimum number of steps needed to update the real DOM, eliminating unnecessary costly changes. This process is also referred to as **reconciliation**.\n\nReact implements a heuristic O(n) algorithm based on two assumptions:\n\n1. Two elements of different types will produce different trees.\n1. The developer can hint at which child elements may be stable across different renders with a key prop.\"\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Diff Algorithm is implemented in Reactjs?\n\nThe main work of a **diff algorithm** is to find a heuristic to change anything from a state to another. When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.\n\n**1. Elements Of Different Types:**\n\nWhenever the root elements have different types, React will tear down the old tree and build the new tree from scratch.\nWhen tearing down a tree, old DOM nodes are destroyed. Component instances receive `componentWillUnmount()`.\n\nWhen building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive `UNSAFE_componentWillMount()` and then `componentDidMount()`. Any state associated with the old tree is lost.\n\n**2. DOM Elements Of The Same Type:**\n\nWhen comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes.\n\n**Example:** By comparing these two elements, React knows to only modify the `className` on the underlying DOM node.\n\n```js\n\u003cdiv className=\"before\" title=\"React JS\" /\u003e\n\n\u003cdiv className=\"after\" title=\"React JS\" /\u003e\n```\n\n**3. Component Elements Of The Same Type:**\n\nWhen a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls `UNSAFE_componentWillReceiveProps()`, `UNSAFE_componentWillUpdate()` and `componentDidUpdate()` on the underlying instance.\n\n**Recursing On Children:**\n\nBy default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there\\'s a difference.\n\nFor example, when adding an element at the end of the children, converting between these two trees works well:\n\n```js\n\u003cul\u003e\n  \u003cli\u003efirst\u003c/li\u003e\n  \u003cli\u003esecond\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cul\u003e\n  \u003cli\u003efirst\u003c/li\u003e\n  \u003cli\u003esecond\u003c/li\u003e\n  \u003cli\u003ethird\u003c/li\u003e\n\u003c/ul\u003e\n```\n\nReact will match the two `\u003cli\u003efirst\u003c/li\u003e` trees, match the two `\u003cli\u003esecond\u003c/li\u003e` trees, and then insert the `\u003cli\u003ethird\u003c/li\u003e` tree.\n\n**Keys:**\n\nWhen children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a key to our inefficient example above can make the tree conversion efficient:\n\n```js\n\u003cul\u003e\n  \u003cli key=\"2015\"\u003eDuke\u003c/li\u003e\n  \u003cli key=\"2016\"\u003eVillanova\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cul\u003e\n  \u003cli key=\"2014\"\u003eConnecticut\u003c/li\u003e\n  \u003cli key=\"2015\"\u003eDuke\u003c/li\u003e\n  \u003cli key=\"2016\"\u003eVillanova\u003c/li\u003e\n\u003c/ul\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is reconciliation in React?\n\nReconciliation is the process through which React updates the DOM.\n\nAs a developer we are creating tree of components, react then takes this tree, process it and we get a Virtual DOM that it\\'s kept in memory. When there is an update in our application (e.g. change in `state` or `props`) react will take the updated Virtual DOM and compares it with the old one Virtual DOM, then decides what and how should be changed. This procedure is repeated all over again.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/reconciliation.jpg\" alt=\"reconciliation\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nAlso synced versions between Virtual DOM and \"real\" DOM are served by libraries such as **ReactDOM**. React needs to be very fast at comparing those trees, so it uses **heuristic algorithm** with complexity of **O(n)**, so this says for 1000 nodes we need 1000 comparasions. This approach is used instead of state of the art algorithms, which have complexity of **O(n\\^3)** =\u003e for 1000 nodes we need 1 bilion comparasions.\n\n**Example:** Let\\'s build a simple component that adds two numbers. The numbers will be entered in an input field.\n\n```js\nclass App extends React.Component {\n  \n  state = {\n    result: '',\n    entry1: '',\n    entry2: ''\n  }\n\n  handleEntry1 = (event) =\u003e {\n    this.setState({entry1: event.target.value})\n  }\n  \n  handleEntry2 = (event) =\u003e {\n    this.setState({entry2: event.target.value})\n  }\n\n  handleAddition = (event) =\u003e {\n    const firstInt = parseInt(this.state.entry1)\n    const secondInt = parseInt(this.state.entry2)\n    this.setState({result: firstInt + secondInt })\n  }\n  \n  render() {\n    const { entry1, entry2, result } = this.state\n    return(\n      \u003cdiv\u003e  \n        \u003cdiv\u003e\n          Result: { result }\n        \u003c/div\u003e\n        \u003cspan\u003e\u003cinput type='text' onChange={this.handleEntry1} /\u003e\u003c/span\u003e\n        \u003cbr /\u003e\n        \u003cbr /\u003e\n        \u003cspan\u003e\u003cinput type='text' onChange={this.handleEntry2} /\u003e\u003c/span\u003e\n        \u003cdiv\u003e\n          \u003cbutton onClick={this.handleAddition} type='submit'\u003eAdd\u003c/button\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cApp /\u003e, document.getElementById(\"root\"))\n```\n\nWhen an entry is made in the first input field, React creates a new tree. The new tree which is the virtual DOM will contain the new state for **entry1**. Then, React compares the virtual DOM with the old DOM and, from the comparison, it figures out the difference between both DOMs and makes an update to only the part that is different. A new tree is created each time the state of App component changes — when a value is entered in either of the inputs field, or when the button is clicked.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are portals in React?\n\nPortals provide a quick and seamless way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.\n\nNormally, a functional or a class component renders a tree of React elements (usually generated from JSX). The React element defines how the DOM of the parent component should look.\n\n```js\nReactDOM.createPortal(child, container)\n```\n\n**Features:**\n\n* It transports its children component into a new React portal which is appended by default to `document.body`.\n* It can also target user specified DOM element.\n* It supports server-side rendering\n* It supports returning arrays (no wrapper div\\'s needed)\n* It uses `\u003cPortal /\u003e` and `\u003cPortalWithState /\u003e` so there is no compromise between flexibility and convenience.\n\n**Installation:**\n\n```bash\nnpm install react-portal --save\n```\n\n**Example:**\n\n```js\n/**\n * React Portal\n */\nimport PortalExample from \"./PortalExample.js\";\n\nexport default function App() {\n  return (\n    \u003cdiv\u003e\n      \u003ch2\u003eReact Component Example\u003c/h2\u003e\n      \u003cPortalExample /\u003e\n    \u003c/div\u003e\n  );\n}\n\n\n/**\n * Portal Component\n */\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\n\n\nexport default function PortalExample() {\n  return ReactDOM.createPortal(\n    \u003ch2\u003eReact Portal Example\u003c/h2\u003e,\n    document.getElementById(\"portal-root\")\n  );\n}\n```\n\nNow, open the Index.html file and add a `\u003cdiv id=\"portal-root\"\u003e\u003c/div\u003e` element to access the child component outside the root node.\n\n```html\n\u003c!-- index.html --\u003e\n\n\u003c!DOCTYPE html\u003e  \n\u003chtml lang=\"en\"\u003e  \n  \u003chead\u003e  \n    \u003cmeta charset=\"utf-8\" /\u003e  \n    \u003clink rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" /\u003e  \n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /\u003e  \n    \u003cmeta name=\"theme-color\" content=\"#000000\" /\u003e  \n    \u003clink rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" /\u003e  \n    \u003ctitle\u003eReact App using Portal\u003c/title\u003e  \n  \u003c/head\u003e  \n  \u003cbody\u003e  \n    \u003cnoscript\u003eIt is required to enable JavaScript to run this app.\u003c/noscript\u003e  \n    \u003cdiv id=\"root\"\u003e\u003c/div\u003e  \n    \u003cdiv id=\"portal-root\"\u003e\u003c/div\u003e  \n  \u003c/body\u003e  \n\u003c/html\u003e  \n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/keen-clarke-y10jp2?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is ReactDOMServer?\n\nThe **ReactDOMServer** object enables you to render components to static markup. Typically, it\\'s used on a Node server:\n\n```js\n// ES modules\nimport ReactDOMServer from 'react-dom/server'\n// CommonJS\nvar ReactDOMServer = require('react-dom/server')\n```\n\nThe **Server-side rendering (SSR)** is a popular technique for rendering a client-side single page application (SPA) on the server and then sending a fully rendered page to the client. This allows for dynamic components to be served as static HTML markup.\n\n* It allows your site to have a faster first page load time, which is the key to a good user experience\n* This approach can be useful for search engine optimization (SEO) when indexing does not handle JavaScript properly.\n* It is great when people share a page of your site on social media, as they can easily gather the metadata needed to nicely share the link (images, title, description..)\n\n**Example:**\n\n**Creating an Express Server:**\n\n```bash\nnpm install express\n```\n\nAll the content inside the build folder is going to be served as-is, statically by Express.\n\n```js\n// server/server.js\n\nimport path from 'path'\nimport fs from 'fs'\n\nimport express from 'express'\nimport React from 'react'\nimport ReactDOMServer from 'react-dom/server'\n\nimport App from '../src/App'\n\nconst PORT = 8080\nconst app = express()\n\nconst router = express.Router()\n\nconst serverRenderer = (req, res, next) =\u003e {\n  fs.readFile(path.resolve('./build/index.html'), 'utf8', (err, data) =\u003e {\n    if (err) {\n      console.error(err)\n      return res.status(500).send('An error occurred')\n    }\n    return res.send(\n      data.replace(\n        '\u003cdiv id=\"root\"\u003e\u003c/div\u003e',\n        `\u003cdiv id=\"root\"\u003e${ReactDOMServer.renderToString(\u003cApp /\u003e)}\u003c/div\u003e`\n      )\n    )\n  })\n}\nrouter.use('^/$', serverRenderer)\n\nrouter.use(\n  express.static(path.resolve(__dirname, '..', 'build'), { maxAge: '30d' })\n)\n\n// tell the app to use the above rules\napp.use(router)\n\n// app.use(express.static('./build'))\napp.listen(PORT, () =\u003e {\n  console.log(`SSR running on port ${PORT}`)\n})\n```\n\nNow, in the client application, in your src/index.js, instead of calling `ReactDOM.render()`:\n\n```js\nReactDOM.render(\u003cApp /\u003e, document.getElementById('root'))\n```\n\ncall ReactDOM.hydrate(), which is the same but has the additional ability to attach event listeners to existing markup once React loads:\n\n```js\nReactDOM.hydrate(\u003cApp /\u003e, document.getElementById('root'))\n```\n\nAll the Node.js code needs to be transpiled by Babel, as server-side Node.js code does not know anything about JSX, nor ES Modules (which we use for the include statements).\n\n**Babel Package:**\n\n```bash\nnpm install @babel/register @babel/preset-env @babel/preset-react ignore-styles\n```\n\nLet\\'s create an entry point in `server/index.js`:\n\n```js\nrequire('ignore-styles')\n\nrequire('@babel/register')({\n  ignore: [/(node_modules)/],\n  presets: ['@babel/preset-env', '@babel/preset-react']\n})\n\nrequire('./server')\n```\n\nBuild the React application, so that the build/ folder is populated and run this:\n\n```bash\n# Build App\nnpm run build\n\n# Run App on Express\nnode server/index.js\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can automated tooling be used to improve the accessibility of a React application?\n\nThere are two main categories of automated tools that can be used to identify accessibility issues:\n\n**1. Static Analysis Tools:**\n\nLinting tools like `ESLint` can be used with plugins such as `eslint-plugin-jsx-a11y` to analyse React projects at a component level. Static analysis tools run very quickly, so they bring a good benefit at a low cost.\n\n**2. Browser Tools:**  \n\nBrowser accessibility tools such as `aXe` and `Google Lighthouse` perform automated accessibility at the app level. This can discover more real-world issues, because a browser is used to simulate the way that a user interacts with a website.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n#### Q. How to do SEO on react?\n#### Q. How to create a Micro Frontend application using React?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 1. REDUX OVERVIEW\n\n\u003cbr/\u003e\n\n## Q. What is Redux?\n\nRedux is a state management tool. While it is mostly used with React, it can be used with any other JavaScript framework or library. With Redux, the state of your application is kept in a store, and each component can access any state that it needs from this store.\n\n**Architecture:**\n\nIn Redux architecture, application event is denoted as an Action, which is dispatched to the reducer, the pure function. Then reducer updates the centralized store with new data based on the kind of action it receives. Store creates a new state and sends an update to view. At that time, the view was recreated to reflect the update.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-architecture.png\" alt=\"Redux Architecture\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nThere is a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another. There are three building parts: `actions`, `store`, and `reducers`.\n\n## Q. What are the benefits of using Redux?\n\n**1. State transfer:**\n\nState is stored together in a single place called the ‘store.’ While you do not need to store all the state variables in the ‘store,’ it is especially important to when state is being shared by multiple components or in a more complex architecture. It also allows you to call state data from any component easily.\n\n**2. Predictability:**\n\nRedux is “a predictable state container for Javascript apps.” Because reducers are pure functions, the same result will always be produced when a state and action are passed in.\n\n**3. Maintainability:**\n\nRedux provides a strict structure for how the code and state should be managed, which makes the architecture easy to replicate and scale for somebody who has previous experience with Redux.\n\n**4. Ease of testing and debugging:**\n\nRedux makes it easy to test and debug your code since it offers powerful tools such as Redux DevTools in which you can time travel to debug, track your changes, and much more to streamline your development process.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are redux core concepts?\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-components.jpg\" alt=\"Redux Components\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**1. Actions in Redux:**\n\nAction is static information about the event that initiates a state change. When you update your state with Redux, you always start with an action. Actions are in the form of Javascript objects, containing a `type` and an optional `payload`. Actions are sent using the `store.dispatch()` method. Actions are created via an action creator.\n\n**Action creators:** are simple functions that help to create actions. They are functions that return action objects, and then, the returned object is sent to various reducers in the application.\n\n**2. Reducers in Redux:**\n\nReducers are pure functions that take the current state of an application, perform an action, and return a new state. These states are stored as objects, and they specify how the state of an application changes in response to an action sent to the store.\n\nIt is based on the reduce function in JavaScript, where a single value is calculated from multiple values after a callback function has been carried out.\n\n**combine multiple reducers:** The `combineReducers()` helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.\n\n**Syntax:**\n\n```js\nconst rootReducers = combineReducer(reducer1, reducer2)\n```\n\n**3. Store in Redux:**\n\nA Store is an object that holds the whole state tree of your application. The Redux store is the application state stored as objects. Whenever the store is updated, it will update the React components subscribed to it. The store has the responsibility of storing, reading, and updating state.\n\nWhen using Redux with React, states will no longer need to be lifted up; thus, it makes it easier to trace which action causes any change.\n\n**4. Dispatch:**\n\nDispatch is a method that triggers an action with type and payload to Reducer.\n\n```js\nstore.dispatch() \n```\n\n**5. Subscribe:**\n\nSubscribe is a method that is used to subscribe data/state from the Store.\n\n```js\nstore.subscribe()\n```\n\n**6. Provider:**\n\nThe Provider is a component that has a reference to the Store and provides the data from the Store to the component it wraps.\n\n**7. Connect:**\n\nConnect is a function that communicates with the Provider.\n\n**8. Middleware:**\n\nMiddleware is the suggested way to extend Redux with custom functionality. Middlewares are used to dispatch async functions. We configure Middleware\\'s while creating a store.\n\n**Syntax:**\n\n```js\nconst store = createStore(reducers, initialState, middleware);\n```\n\n**Example:**\n\n```js\n/**\n * React Redux Simple Example\n */\nimport React from \"react\";\nimport \"./styles.css\";\nimport { signIn, signOut } from \"./actions\";\nimport { useSelector, useDispatch } from \"react-redux\";\n\nexport default function App() {\n  const isLogged = useSelector((state) =\u003e state.isLogged);\n  const dispatch = useDispatch();\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003ch1\u003eReact Redux Example\u003c/h1\u003e\n      \u003cbutton onClick={() =\u003e dispatch(signIn())}\u003eSignIn\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch(signOut())}\u003eSignOut\u003c/button\u003e\n\n      {isLogged ? \u003ch2\u003eYou are now logged in...\u003c/h2\u003e : \"\"}\n    \u003c/div\u003e\n  );\n}\n```\n\n```js\n/**\n * Actions\n */\nexport const signIn = () =\u003e {\n  return {\n    type: \"SIGN_IN\"\n  };\n};\n\nexport const signOut = () =\u003e {\n  return {\n    type: \"SIGN_OUT\"\n  };\n};\n```\n\n```js\n/**\n * Reducers\n */\nimport { combineReducers } from \"redux\";\n\nconst loggedReducer = (state = false, action) =\u003e {\n  switch (action.type) {\n    case \"SIGN_IN\":\n      return true;\n    case \"SIGN_OUT\":\n      return false;\n    default:\n      return state;\n  }\n};\n\nconst allReducers = combineReducers({\n  isLogged: loggedReducer\n});\n\nexport default allReducers;\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/react-redux-simple-example-y3i7u6?file=/src/App.js)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between presentational component and container component in react redux?\n\n**1. Container Components:**\n\n* Container components are primarily concerned with how things work\n* They rarely have any HTML tags of their own, aside from a wrapping `\u003cdiv\u003e`\n* They are often stateful\n* They are responsible for providing data and behavior to their children (usually presentational components)\n\nContainer is an informal term for a React component that is `connect`-ed to a redux store. Containers receive Redux state updates and `dispatch` actions, and they usually don\\'t render DOM elements; they delegate rendering to **presentational** child components.\n\n**Example:**\n\n```js\nclass Collage extends Component {\n   constructor(props) {\n      super(props);\n\n      this.state = {\n         images: []\n      };\n   }\n   componentDidMount() {\n      fetch('/api/current_user/image_list')\n         .then(response =\u003e response.json())\n         .then(images =\u003e this.setState({images}));\n   }\n   render() {\n      return (\n         \u003cdiv className=\"image-list\"\u003e\n            {this.state.images.map(image =\u003e {\n               \u003cdiv className=\"image\"\u003e\n                  \u003cimg src={book.image_url} /\u003e\n               \u003c/div\u003e\n            })}\n         \u003c/div\u003e\n      )\n   }\n}\n```\n\n**2. Presentational Components:**\n\n* Presentational Components are primarily concerned with how things look\n* Probably only contain a render method and little else logic\n* They do not know how to load or alter the data that they render\n* They are best written as stateless functional components\n\n**Example:**\n\n```js\n//defining the component as a React Component\nclass Image extends Component {\n   render() {\n      return \u003cimg src={this.props.image} /\u003e;\n   }\n}\nexport default Image\n//defining the component as a constant\nconst Image = props =\u003e (\n   \u003cimg src={props.image} /\u003e\n)\nexport default Image\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 2. REDUX SETUP\n\n\u003cbr/\u003e\n\n## Q. How to add redux into create react app?\n\nRedux is the most popular State container library for frontend apps. It helps you manage your state in a predictable and easy way.\n\n**Installation:**\n\nReact Redux 8.x requires React 16.8.3 or later / React Native 0.59 or later, in order to make use of React Hooks.\n\n```js\n# Redux + Plain JS template\nnpx create-react-app my-app --template redux\n\n# Redux + TypeScript template\nnpx create-react-app my-app --template redux-typescript\n```\n\n**An Existing React App:**\n\nTo use React Redux with your React app, install it as a dependency:\n\n```js\n# If you use npm:\nnpm install redux react-redux redux-thunk --save\n\n# Or if you use Yarn:\nyarn add redux react-redux redux-thunk --save\n```\n\n**Folder structure:**\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-setup.png\" alt=\"React Redux Folder structure\" width=\"200px\" /\u003e\n\u003c/p\u003e\n\n**Reference:**\n\n* *[https://react-redux.js.org/introduction/getting-started](https://react-redux.js.org/introduction/getting-started)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to structure Redux top level directories?\n\nThe most of the applications has several top-level directories as below:\n\n* **Components** - Contains all 'dumb' or presentational components, consisting only of HTML and styling.\n* **Containers** - Contains all corresponding components with logic in them. Each container will have one or more component depending on the view represented by the container.\n* **Actions** - All Redux actions\n* **Reducers** - All Redux reducers\n* **API** - API connectivity related code. Handler usually involves setting up an API connector centrally with authentication and other necessary headers.\n* **Utils** - Other logical codes that are not React specific. For example, authUtils would have functions to process the JWT token from the API to determine the user scopes.\n* **Store** - Used for redux store initialization.\n\n**Example:**\n\n```js\n└── src\n    ├── actions\n    │   ├── articleActions.js\n    │   ├── categoryActions.js\n    │   └── userActions.js\n    ├── api\n    │   ├── apiHandler.js\n    │   ├── articleApi.js\n    │   ├── categoryApi.js\n    │   └── userApi.js\n    ├── components\n    │   ├── ArticleComponent.jsx\n    │   ├── ArticleListComponent.jsx\n    │   ├── CategoryComponent.jsx\n    │   ├── CategoryPageComponent.jsx\n    │   └── HomePageComponent.jsx\n    ├── containers\n    │   ├── ArticleContainer.js\n    │   ├── CategoryPageContainer.js\n    │   └── HomePageContainer.js\n    ├── index.js\n    ├── reducers\n    │   ├── articleReducer.js\n    │   ├── categoryReducer.js\n    │   └── userReducer.js\n    ├── routes.js\n    ├── store.js\n    └── utils\n        └── authUtils.js\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 3. REDUX DATA FLOW\n\n\u003cbr/\u003e\n\n## Q. How to set the dataflow using react with redux?\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-data-flow.gif\" alt=\"Redux Data Flow\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\nRedux offers this data sharing of components possible by maintaining one single state in the store. A single source of truth. All the components which want to get state data at some point are subscribed to the store and they will receive the state each time it gets updated.\n\nRedux has five main entities. Action Creators, Dispatching Function, Reducers, State and Store.\n\n* An action is dispatched when a user interacts with the application.\n* The root reducer function is called with the current state and the dispatched action. The root reducer may divide the task among smaller reducer functions, which ultimately returns a new state.\n* The store notifies the view by executing their callback functions.\n* The view can retrieve updated state and re-render again.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the three principles that Redux follows?\n\nRedux can be described in three fundamental principles:\n\n**1. Single source of truth:**\n\n\u003e The state of your whole application is stored in an object tree inside a single store.\n\nThis makes it easy to create universal apps, as the state from your server can be serialized and hydrated into the client with no extra coding effort. A single state tree also makes it easier to debug or inspect an application; it also enables you to persist your app\\'s state in development, for a faster development cycle.\n\n**Example:**\n\n```js\nconsole.log(store.getState())\n\n/* Prints\n{\n  visibilityFilter: 'SHOW_ALL',\n  todos: [\n    {\n      text: 'Consider using Redux',\n      completed: true,\n    },\n    {\n      text: 'Keep all state in a single tree',\n      completed: false\n    }\n  ]\n}\n*/\n```\n\n**2. State is read-only:**\n\n\u003e The only way to change the state is to emit an action, an object describing what happened.\n\nThis ensures that neither the views nor the network callbacks will ever write directly to the state. Instead, they express an intent to transform the state. Because all changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for.\n\n**Example:**\n\n```js\nstore.dispatch({\n  type: 'COMPLETE_TODO',\n  index: 1\n})\n\nstore.dispatch({\n  type: 'SET_VISIBILITY_FILTER',\n  filter: 'SHOW_COMPLETED'\n})\n```\n\n**3. Changes are made with pure functions:**\n\n\u003e To specify how the state tree is transformed by actions, you write pure reducers.\n\nReducers are just pure functions that take the previous state and an action, and return the next state. Remember to return new state objects, instead of mutating the previous state. You can start with a single reducer, and as your app grows, split it off into smaller reducers that manage specific parts of the state tree.\n\n```js\nimport { combineReducers, createStore } from 'redux'\n\nfunction visibilityFilter(state = 'SHOW_ALL', action) {\n  switch (action.type) {\n    case 'SET_VISIBILITY_FILTER':\n      return action.filter\n    default:\n      return state\n  }\n}\n\nfunction todos(state = [], action) {\n  switch (action.type) {\n    case 'ADD_TODO':\n      return [\n        ...state,\n        {\n          text: action.text,\n          completed: false\n        }\n      ]\n    case 'COMPLETE_TODO':\n      return state.map((todo, index) =\u003e {\n        if (index === action.index) {\n          return Object.assign({}, todo, {\n            completed: true\n          })\n        }\n        return todo\n      })\n    default:\n      return state\n  }\n}\n\nconst reducer = combineReducers({ visibilityFilter, todos })\nconst store = createStore(reducer)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do you understand by \"Single source of truth\" in Redux?\n\nThe single source of truth is our state tree, that is not rewritten or reshaped. It gives us the availability to easily retrieve information in constant time and maintain a clean structure for the state of our application.\n\nIn React-Redux applications, when your Redux is a single source of truth, it means that the only way to change your data in UI is to dispatch redux action which will change state within redux reducer. And your React components will watch this reducer and if that reducer changes, then UI will change itself too. But never other way around, because Redux state is single source of truth.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-state.png\" alt=\"Redux State\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nA practical example would be that you have Redux store which contains items you want to display. In order to change list of items to be displayed, you don\\'t change this data anywhere else other than store. And if that is changed, everything else related to it, should change as well.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the features of Workflow in Redux?\n\nWhen using Redux with React, states will no longer need to be lifted up. Everything is handled by Redux. Redux simplifies the app and makes it easier to maintain.\n\n* Redux offers a solution for storing all your application state in one place, called a **store**.\n* Components then **dispatch** state changes to the store, not directly to other components.\n* The components that need to be aware of state changes can subscribe to the store.\n* The **store** can be thought of as a \"middleman\" for all state changes in the application.\n* With Redux involved, components don\\'t communicate directly with each other. Rather, all state changes must go  through the single source of truth, the **store**.\n\n**Core Principal:**\n\nRedux has three core principals:\n\n**1. Single Source of Truth**: The state of your whole application is stored in an object tree within a single **store**.  \n**2. State Is Read-Only**: The only way to change the state is to dispatch an **action**, an object describing what happened.  \n**3. Changes Are Made With Pure Functions**: To specify how the state tree is transformed by actions, you write pure **reducers**.  \n\n**Redux Workflow:**\n\nRedux allows you to manage the state of the application using Store. A child component can directly access the state from the Store.\n\nThe following are details of how Redux works:\n\n* When UI Event triggers (OnClick, OnChange, etc) it can dispatch Actions based on the event.\n* Reducers process Actions and return a new state as an Object.\n* The new state of the whole application goes into a single Store.\n* Components can easily subscribe to the Store.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-workflow.png\" alt=\"Redux Workflow\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4. REDUX STORE\n\n\u003cbr/\u003e\n\n## Q. What is a store in Redux?\n\nA store is an object that holds the whole state tree of your application. The Redux store is the application state stored as objects. Whenever the store is updated, it will update the React components subscribed to it. The store has the responsibility of storing, reading, and updating state.\n\n**Example:**\n\n```js\n/**\n * store in Redux\n */\nimport { createRoot } from \"react-dom/client\";\nimport { Provider } from \"react-redux\";\nimport { createStore } from \"redux\";\nimport rootReducer from \"./reducers\";\nimport App from \"./components/App\";\n\nconst rootElement = document.getElementById(\"root\");\nconst root = createRoot(rootElement);\n\n// create store\nconst store = createStore(rootReducer);\n\nroot.render(\n  \u003cprovider store=\"{store}\"\u003e\n    \u003cApp /\u003e\n  \u003c/provider\u003e\n);\n```\n\nWhen using Redux with React, states will no longer need to be lifted up; thus, it makes it easier to trace which action causes any change.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the best way to access redux store outside a react component?\n\nTo access redux store outside a react component, Redux `connect` function works great for regular React components.\n\nIn the examples below shows how to access a JWT token from the Redux store.\n\n**Option 1:** Export the Store\n\n```js\nimport { createStore } from 'redux'\nimport reducer from './reducer'\n\nconst store = createStore(reducer)\n\nexport default store\n```\n\nHere, we are creating the store and exporting it. This will make it available to other files. Here we\\'ll see an `api` file making a call where we need to pass a JWT token to the server:\n\n```js\nimport store from './store'\n\nexport function getProtectedThing() {\n  // grab current state\n  const state = store.getState()\n\n  // get the JWT token out of it\n  // (obviously depends on how your store is structured)\n  const authToken = state.currentUser.token\n\n  // Pass the token to the server\n  return fetch('/user/thing', {\n    method: 'GET',\n    headers: {\n      Authorization: `Bearer ${authToken}`\n    }\n  }).then(res =\u003e res.json())\n}\n```\n\n**Option 2:** Pass the value from a React Component\n\nIt\\'s simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the `connect()` function from React Redux, and supply a `mapStateToProps()` function that pulls out the data.\n\n```js\nimport React from 'react'\nimport { connect } from 'react-redux'\nimport * as api from 'api'\n\nconst ItemList = ({ authToken, items }) =\u003e {\n  return (\n    \u003cul\u003e\n      {items.map(item =\u003e (\n        \u003cli key={item.id}\u003e\n          {item.name}\n          \u003cbutton\n            onClick={\n              () =\u003e api.deleteItem(item, authToken)\n            }\u003e\n            DELETE THIS ITEM\n          \u003c/button\u003e\n        \u003c/li\u003e\n      )}\n    \u003c/ul\u003e\n  )\n}\n\nconst mapStateToProps = state =\u003e ({\n  authToken: state.currentUser \u0026\u0026 state.currentUser.authToken,\n  items: state.items\n})\n\nexport connect(mapStateToProps)(ItemList)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Should all component states be kept in Redux Store\n\nThere is no \"right\" answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as \"is this dropdown currently open\", inside a component\\'s internal state.\n\nSome common rules for determining what kind of data should be put into Redux:\n\n* Do other parts of the application needs data to be shared.\n* Is the same data being used to drive multiple components.\n* Do you want to cache the data.\n* Do you want to keep this data consistent while hot-reloading UI components.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use connect from React Redux?\n\nThe `connect()` function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.\n\nIt does not modify the component class passed to it; instead, it returns a new, connected component class that wraps the component you passed in.\n\n* **Use `mapStateToProps()`:** It maps the state variables from your store to the props that you specify.\n* **Connect props to container:** The object returned by the `mapStateToProps` function is connected to the container.\n\n**Example:**\n\n```js\nimport React from 'react'\nimport { connect } from 'react-redux'\n\nclass App extends React.Component {\n  render() {\n    return \u003cdiv\u003e{this.props.containerData}\u003c/div\u003e\n  }\n}\n\nfunction mapStateToProps(state) {\n  return { containerData: state.data }\n}\n\nexport default connect(mapStateToProps)(App)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 5. REDUX ACTIONS\n\n\u003cbr/\u003e\n\n## Q. What is an action in Redux?\n\n**Actions** are plain JavaScript objects or **payloads** of information that send data from your application to your store. They are the only source of information for the store. Actions must have a type property that indicates the type of action being performed.\n\nAn action is an object that contains two keys and their values. The state update that happens in the reducer is always dependent on the value of action.type.\n\n**Example:**\n\n```js\nconst action = {\n  type: 'NEW_CONTACT',\n  name: 'Alex K',\n  location: 'Lagos Nigeria',\n  email: 'alex@example.com'\n}\n```\n\nThere is typically a payload value that contains what the user is sending and would be used to update the state of the application. It is important to note that action.type is required, but action.payload is optional. Making use of payload brings a level of structure to how the action object looks like.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create action creators react with redux?\n\n**1. Action Type:**\n\nAn action type is a string that simply describes the type of an action. They\\'re commonly stored as constants or collected in enumerations to help reduce typos.\n\n**Example:**\n\n```js\nexport const Actions = {\n  GET_USER_DETAILS_REQUEST: 'GET_USER_DETAILS_REQUEST',\n  GET_USER_DETAILS_SUCCESS: 'GET_USER_DETAILS_SUCCESS',\n  GET_USER_DETAILS_FAILURE: 'GET_USER_DETAILS_FAILURE',\n  ...\n}\n```\n\n**2. Action:**\n\nAn action is like a message that we send (i.e. dispatch) to our central Redux store. It can literally be anything. But ideally we want to stick to an agreed-upon pattern. And the standard pattern is as follows (this is a TypeScript type declaration):\n\n**Example:**\n\n```ts\ntype Action = {\n    type: string;    // Actions MUST have a type\n    payload?: any;   // Actions MAY have a payload\n    meta?: any;      // Actions MAY have meta information\n    error?: boolean; // Actions MAY have an error field\n                     // when true, payload SHOULD contain an Error\n}\n```\n\nAn action to fetch the user named \"Ram\" might look something like this\n\n```js\n{\n    type: 'GET_USER_DETAILS_REQUEST',\n    payload: 'Ram'\n}\n```\n\n**3. Action Creator:**\n\nWhen writing basic Redux, an action creator simply returns an action. You would typically dispatch the action to your store immediately.\n\n**Example:**\n\n```js\nexport const getUserDetailsRequest = id =\u003e ({\n  type: Actions.GET_USER_DETAILS_REQUEST,\n  payload: id,\n})\n```\n\n```js\nstore.dispatch(getUserDetailsRequest('Ram'))\n```\n\nAlthough, realistically, you\\'ll be doing this via dispatch properties that are passed into a React component like this:\n\n```js\n// ES6\nexport const mapDispatchToProps = dispatch =\u003e ({\n  onClick: () =\u003e dispatch(getUserDetailsRequest('Ram'))\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to dispatch an action on load?\n\nYou can dispatch an action in `componentDidMount()` method and in `render()` method you can verify the data.\n\n**Example:**\n\n```js\n/**\n * Dispatch an action on load\n */\nclass App extends Component {\n  componentDidMount() {\n    this.props.fetchData()\n  }\n\n  render() {\n    return this.props.isLoaded\n      ? \u003cdiv\u003e{'Loaded'}\u003c/div\u003e\n      : \u003cdiv\u003e{'Not Loaded'}\u003c/div\u003e\n  }\n}\n\nconst mapStateToProps = (state) =\u003e ({\n  isLoaded: state.isLoaded\n})\n\nconst mapDispatchToProps = { fetchData }\n\nexport default connect(mapStateToProps, mapDispatchToProps)(App)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 6. REDUX REDUCERS\n\n\u003cbr/\u003e\n\n## Q. What is reducers in redux?\n\nReducers are pure functions that take the current state of an application, perform an action, and return a new state. These states are stored as objects, and they specify how the state of an application changes in response to an action sent to the store.\n\nIt is based on the reduce function in JavaScript, where a single value is calculated from multiple values after a callback function has been carried out.\n\n**Example:**\n\n```js\nconst LoginComponent = (state = initialState, action) =\u003e {\n    switch (action.type) {\n\n      // This reducer handles any action with type \"LOGIN\"\n      case \"LOGIN\":\n          return state.map(user =\u003e {\n              if (user.username !== action.username) {\n                  return user\n              }\n\n              if (user.password == action.password) {\n                  return {\n                      ...user,\n                      login_status: \"LOGGED IN\"\n                  }\n              }\n          });\n      default:\n          return state;\n      }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the role of Reducer?\n\nA reducer is a function that determines changes to an application\\'s state. It uses the action it receives to determine this change. Redux manage an application\\'s state changes in a single store so that they behave consistently. Redux relies heavily on reducer functions that take the previous state and an action in order to execute the next state.\n\n**1. State:**\n\nState changes are based on a user\\'s interaction, or even something like a network request. If the application\\'s state is managed by Redux, the changes happen inside a reducer function — this is the only place where state changes happen. The reducer function makes use of the initial state of the application and something called action, to determine what the new state will look like.\n\n**Syntax:**\n\n```js\nconst contactReducer = (state = initialState, action) =\u003e {\n  // Do something\n}\n```\n\n**2. State Parameter:**\n\nThe state parameter that gets passed to the reducer function has to be the current state of the application. In this case, we\\'re calling that our initialState because it will be the first (and current) state and nothing will precede it.\n\n```js\ncontactReducer(initialState, action)\n```\n\n**Example:**\n\nLet\\'s say the initial state of our app is an empty list of contacts and our action is adding a new contact to the list.\n\n```js\nconst initialState = {\n  contacts: []\n}\n```\n\n**3. Action Parameter:**\n\nAn action is an object that contains two keys and their values. The state update that happens in the reducer is always dependent on the value of action.type.\n\n```js\nconst action = {\n  type: 'NEW_CONTACT',\n  name: 'Alex K',\n  location: 'Lagos Nigeria',\n  email: 'alex@example.com'\n}\n```\n\nThere is typically a `payload` value that contains what the user is sending and would be used to update the state of the application. It is important to note that `action.type` is required, but `action.payload` is optional. Making use of `payload` brings a level of structure to how the action object looks like.\n\n**4. Updating State:**\n\nThe state is meant to be immutable, meaning it shouldn\\'t be changed directly. To create an updated state, we can make use of `Object.assign()` or opt for the **spread operator**.\n\n**Example:**\n\n```js\nconst contactReducer = (state, action) =\u003e {\n  switch (action.type) {\n    case 'NEW_CONTACT':\n    return {\n        ...state, contacts:\n        [...state.contacts, action.payload]\n    }\n    default:\n      return state\n  }\n}\n```\n\nThis ensures that the incoming state stays intact as we append the new item to the bottom.\n\n```js\nconst initialState = {\n  contacts: [{\n    name: 'Alex K',\n    age: 26\n  }]\n}\n\nconst contactReducer = (state = initialState, action) =\u003e {\n  switch (action.type) {\n    case \"NEW_CONTACT\":\n      return Object.assign({}, state, {\n        contacts: [...state.contacts, action.payload]\n      });\n    default:\n      return state\n  }\n}\n\nclass App extends React.Component {\n  constructor(props) {\n    super(props)\n    this.name = React.createRef()\n    this.age = React.createRef()\n    this.state = initialState\n  }\n\n  handleSubmit = e =\u003e {\n    e.preventDefault()\n    const action = {\n      type: \"NEW_CONTACT\",\n      payload: {\n        name: this.name.current.value,\n        age: this.age.current.value\n      }\n    }\n    const newState = contactReducer(this.state, action)\n    this.setState(newState)\n  }\n\n  render() {\n    const { contacts } = this.state\n    return (\n      \u003cdiv className=\"box\"\u003e\n        \u003cdiv className=\"content\"\u003e\n          \u003cpre\u003e{JSON.stringify(this.state, null, 2)}\u003c/pre\u003e\n        \u003c/div\u003e\n\n        \u003cdiv className=\"field\"\u003e\n          \u003cform onSubmit={this.handleSubmit}\u003e\n            \u003cdiv className=\"control\"\u003e\n              \u003cinput className=\"input\" placeholder=\"Full Name\" type=\"text\" ref={this.name} /\u003e\n            \u003c/div\u003e\n            \u003cdiv className=\"control\"\u003e\n              \u003cinput className=\"input\" placeholder=\"Age\" type=\"number\" ref={this.age} /\u003e\n            \u003c/div\u003e\n            \u003cdiv\u003e\n              \u003cbutton type=\"submit\" className=\"button\"\u003eSubmit\u003c/button\u003e\n            \u003c/div\u003e\n          \u003c/form\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\n\nReactDOM.render(\n  \u003cApp /\u003e,\n  document.getElementById('root')\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why should the reducer be a \"pure\" function?\n\nRedux takes a given state (object) and passes it to each reducer in a loop. And it expects a brand new object from the reducer if there are any changes. And it also expects to get the old object back if there are no changes.\n\nRedux simply checks whether the old object is the same as the new object by comparing the memory locations of the two objects. So if you mutate the old object\\'s property inside a reducer, the \"new state\" and the \"old state\" will both point to the same object. Hence Redux thinks nothing has changed! So this won\\'t work.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to split the reducers?\n\nPutting all your update logic into a single reducer function is quickly going to become unmaintainable. While there\\'s no single rule for how long a function should be, it\\'s generally agreed that functions should be relatively short and ideally only do one specific thing. It\\'s good programming practice to take pieces of code that are very long or do many different things, and break them into smaller pieces that are easier to understand.\n\nIn Redux reducer, we can split some of our reducer logic out into another function, and call that new function from the parent function. These new functions would typically fall into one of three categories:\n\n1. Small utility functions containing some reusable chunk of logic that is needed in multiple places (which may or may not be actually related to the specific business logic)\n2. Functions for handling a specific update case, which often need parameters other than the typical (state, action) pair\n3. Functions which handle all updates for a given slice of state. These functions do generally have the typical  (state, action) parameter signature\n\nThese terms will be used to distinguish between different types of functions and different use cases:\n\n* **reducer**: any function with the signature `(state, action) -\u003e newState` (ie, any function that could be used as an argument to `Array.prototype.reduce`)\n* **root reducer**: the reducer function that is actually passed as the first argument to `createStore`. This is the only part of the reducer logic that must have the `(state, action) -\u003e newState` signature.\n* **slice reducer**: a reducer that is being used to handle updates to one specific slice of the state tree, usually done by passing it to `combineReducers`\n* **case function**: a function that is being used to handle the update logic for a specific action. This may actually be a reducer function, or it may require other parameters to do its work properly.\n* **higher-order reducer**: a function that takes a reducer function as an argument, and/or returns a new reducer  function as a result (such as `combineReducers`, or `redux-undo`).\n\n**Benefits:**\n\n* **For fast page loads**\n\nSplitting reducers will have and advantage of loading only required part of web application which in turn makes it very efficient in rendering time of main pages\n\n* **Organization of code**\n\nSplitting reducers on page level or component level will give a better code organization instead of just putting all reducers at one place. Since reducer is loaded only when page/component is loaded will ensure that there are standalone pages which are not dependent on other parts of the application.\n\n* **One page/component**\n\nOne reducer design pattern. Things are better written, read and understood when they are modular. With dynamic reducers, it becomes possible to achieve it.\n\n* **SEO**\n\nWith reducer level code-splitting, reducers can be code split on a split component level which will reduce the loading time of website thereby increasing SEO rankings.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 7. REDUX MIDDLEWARE\n\n\u003cbr/\u003e\n\n## Q. What is Redux Thunk used for?\n\nRedux Thunk is a **middleware** that lets you call action creators that return a function instead of an action object. That function receives the store\\'s dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed. The inner function receives the store methods `dispatch()` and `getState()` as parameters.\n\n**Setup:**\n\n```bash\n# install create react app\nnpm install -g create-react-app\n\n# Create a React App\ncreate-react-app my-simple-async-app\n\n# Switch directory\ncd my-simple-app\n\n# install Redux-Thunk\nnpm install --save redux react-redux redux-thunk\n```\n\n**Example:**\n\nWe are going to use Redux Thunk to asynchronously fetch the most recently updated repos by username from Github using this REST URL:\n\nhttps://api.github.com/users/learning-zone/repos?sort=updated\n\n```js\nimport { applyMiddleware, combineReducers, createStore } from 'redux'\n\nimport thunk from 'redux-thunk'\n\n// actions.js\nexport const addRepos = repos =\u003e ({\n  type: 'ADD_REPOS',\n  repos,\n})\n\nexport const clearRepos = () =\u003e ({ type: 'CLEAR_REPOS' })\n\nexport const getRepos = username =\u003e async dispatch =\u003e {\n  try {\n    const url = `https://api.github.com/users/${username}/repos?sort=updated`\n    const response = await fetch(url)\n    const responseBody = await response.json()\n    dispatch(addRepos(responseBody))\n  } catch (error) {\n    console.error(error)\n    dispatch(clearRepos())\n  }\n}\n\n// reducers.js\nexport const repos = (state = [], action) =\u003e {\n  switch (action.type) {\n    case 'ADD_REPOS':\n      return action.repos\n    case 'CLEAR_REPOS':\n      return []\n    default:\n      return state\n  }\n}\n\nexport const reducers = combineReducers({ repos })\n\n// store.js\nexport function configureStore(initialState = {}) {\n  const store = createStore(reducers, initialState, applyMiddleware(thunk))\n  return store\n}\n\nexport const store = configureStore()\n```\n\n`applyMiddleware(thunk)`: This tells redux to accept and execute functions as return values. Redux usually only accepts objects like { type: 'ADD_THINGS', things: ['list', 'of', 'things'] }.\n\nThe middleware checks if the action\\'s return value is a function and if it is it will execute the function and inject a callback function named dispatch. This way you can start an asynchronous task and then use the dispatch callback to return a regular redux object action some time in the future.\n\n```js\n// This is your typical redux sync action\nfunction syncAction(listOfThings) {\n  return { type: 'ADD_THINGS', things: listOfThings  }\n}\n\n// This would be the async version\n// where we may need to go fetch the\n// list of things from a server before\n// adding them via the sync action\nfunction asyncAction() {\n  return function(dispatch) {\n    setTimeout(function() {\n      dispatch(syncAction(['list', 'of', 'things']))\n    }, 1000)\n  }\n}\n```\n\n**App.js:**\n\n```js\nimport React, { Component } from 'react'\n\nimport { connect } from 'react-redux'\n\nimport { getRepos } from './redux'\n\n// App.js\nexport class App extends Component {\n  state = { username: 'learning-zone' }\n\n  componentDidMount() {\n    this.updateRepoList(this.state.username)\n  }\n\n  updateRepoList = username =\u003e this.props.getRepos(username)\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eI AM AN ASYNC APP!!!\u003c/h1\u003e\n\n        \u003cstrong\u003eGithub username: \u003c/strong\u003e\n        \u003cinput\n          type=\"text\"\n          value={this.state.username}\n          onChange={ev =\u003e this.setState({ username: ev.target.value })}\n          placeholder=\"Github username...\"\n        /\u003e\n        \u003cbutton onClick={() =\u003e this.updateRepoList(this.state.username)}\u003e\n          Get Lastest Repos\n        \u003c/button\u003e\n\n        \u003cul\u003e\n          {this.props.repos.map((repo, index) =\u003e (\n            \u003cli key={index}\u003e\n              \u003ca href={repo.html_url} target=\"_blank\"\u003e\n                {repo.name}\n              \u003c/a\u003e\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n\n      \u003c/div\u003e\n    )\n  }\n}\n\n// AppContainer.js\nconst mapStateToProps = (state, ownProps) =\u003e ({ repos: state.repos })\nconst mapDispatchToProps = { getRepos }\nconst AppContainer = connect(mapStateToProps, mapDispatchToProps)(App)\n\nexport default AppContainer\n```\n\n**index.js:**\n\n```js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport AppContainer from './App'\nimport './index.css'\n\n// Add these imports - Step 1\nimport { Provider } from 'react-redux'\nimport { store } from './redux'\n\n// Wrap existing app in Provider - Step 2\nReactDOM.render(\n  \u003cProvider store={store}\u003e\n    \u003cAppContainer /\u003e\n  \u003c/Provider\u003e,\n  document.getElementById('root')\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are typical middleware choices for handling asynchronous calls in Redux?\n\nBy default, Redux\\'s actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.\n\nThere are three very popular middleware libraries that allow for side effects and asynchronous actions: `Redux Thunk` `Redux Saga` and `Redux Promise`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can I represent \"side effects\" such as AJAX calls? Why do we need things like \"action creators\", \"thunks\", and \"middleware\" to do async behavior?\n\nAny meaningful web app needs to execute complex logic, usually including asynchronous work such as making AJAX requests. That code is no longer purely a function of its inputs, and the interactions with the outside world are known as \"side effects\".\n\nRedux is inspired by functional programming, and out of the box, has no place for side effects to be executed. In particular, reducer functions must always be pure functions of `(state, action) =\u003e newState`. However, Redux\\'s middleware (eg. **Redux Thunk**, **Redux Saga**) makes it possible to intercept dispatched actions and add additional complex behavior around them, including side effects.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Are there any similarities between Redux and RxJS?\n\n**Redux**:\n\nPredictable state container for JavaScript apps. Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger. However, Redux has one, but very significant problem - it doesn\\'t handle asynchronous operations very well by itself.\n\n**RxJS:**\n\nThe Reactive Extensions for JavaScript. RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.\n\nRedux belongs to \"State Management Library\" category of the tech stack, while RxJS can be primarily classified under \"Concurrency Frameworks\".\n\n| Redux                         | RxJS                               |\n|-------------------------------|------------------------------------|\n|Redux is a tool for managing state throughout the application.| RxJS is a reactive programming library|\n|It is usually used as an architecture for UIs. |It is usually used as a tool to accomplish asynchronous tasks in JavaScript.|\n|Redux uses the Reactive paradigm because the Store is reactive. The Store observes actions from a distance, and changes itself.|RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this pattern.|\n\n**Example:** React, Redux and RxJS\n\n```js\nimport React from 'react';  \nimport ReactDOM from 'react-dom';  \nimport { Subject } from 'rxjs/Subject';\n\n// create our stream as a subject so arbitrary data can be sent on the stream\nconst action$ = new Subject();\n\n// Initial State\nconst initState = { name: 'Alex' };\n\n// Redux reducer\nconst reducer = (state, action) =\u003e {  \n  switch(action.type) {\n    case 'NAME_CHANGED':\n      return {\n        ...state,\n        name: action.payload\n      };\n    default:\n      return state;\n  }\n}\n\n// Reduxification\nconst store$ = action$  \n    .startWith(initState)\n    .scan(reducer);\n\n// Higher order function to send actions to the stream\nconst actionDispatcher = (func) =\u003e (...args) =\u003e  \n  action$.next(func(...args));\n\n// Example action function\nconst changeName = actionDispatcher((payload) =\u003e ({  \n  type: 'NAME_CHANGED',\n  payload\n}));\n\n// React view component\nconst App = (props) =\u003e {  \n  const { name } = props;\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003e{ name }\u003c/h1\u003e\n      \u003cbutton onClick={() =\u003e changeName('Alex')} \u003eAlex\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e changeName('John')} \u003eJohn\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n\n// subscribe and render the view\nconst dom =  document.getElementById('app');  \nstore$.subscribe((state) =\u003e  \n    ReactDOM.render(\u003cApp {...state} /\u003e, dom));\n```\n\n**Async actions:**\n\nLet\\'s say we want to do something asynchronous like fetch some information from a rest api all we need to do is send an ajax stream in place of our action payload and then use one of the lodash style stream operators, `flatMap()` to squash the results of the asynchronous operation back onto the `action$` stream.\n\n```js\nimport { isObservable } from './utils';\n\n// Action creator\nconst actionCreator = (func) =\u003e (...args) =\u003e {  \n  const action = func.call(null, ...args);\n  action$.next(action);\n  if (isObservable(action.payload))\n    action$.next(action.payload);\n  return action;\n};\n\n// method called from button click\nconst loadUsers = actionCreator(() =\u003e {  \n  return {\n    type: 'USERS_LOADING',\n    payload: Observable.ajax('/api/users')\n      .map(({response}) =\u003e map(response, 'username'))\n      .map((users) =\u003e ({\n        type: 'USERS_LOADED',\n        payload: users\n      }))\n  };\n});\n\n// Reducer\nexport default function reducer(state, action) {  \n  switch (action.type) {\n    case 'USERS_LOADING':\n      return {\n        ...state,\n        isLoading: true\n      };\n    case 'USERS_LOADED':\n      return {\n        ...state,\n        isLoading: false,\n        users: action.payload,\n      };\n    //...\n  }\n}\n\n// rest of code...\n\n// Wrap input to ensure we only have a stream of observables\nconst ensureObservable = (action) =\u003e  \n  isObservable(action)\n    ? action\n    : Observable.from([action]);\n\n// Using flatMap to squash async streams\nconst action$  \n    .flatMap(wrapActionToObservable)\n    .startWith(initState)\n    .scan(reducer);\n```\n\nThe advantage of swapping the action payload for a stream is so we can send data updates at the start and the end of the async operation\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the differences between redux-saga and redux-thunk?\n\n**1. Redux Thunk:**\n\nRedux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store\\'s dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-thunk.jpeg\" alt=\"Redux Thunk\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n```bash\nnpm i --save react-redux redux redux-logger redux-saga redux-thunk\n```\n\nThunk is a function which optionaly takes some parameters and returns another function, it takes dispatch and getState functions and both of these are supplied by Redux Thunk middleware.\n\nHere is the basic structure of Redux-thunk\n\n```js\nexport const thunkName = parameters =\u003e (dispatch, getState) =\u003e {\n// You can write your application logic here\n}\n```\n\n**Example:**\n\n```js\nimport axios from \"axios\"\nimport GET_LIST_API_URL from \"../config\"\n\nconst fetchList = () =\u003e {\n  return (dispatch) =\u003e {\n    axios.get(GET_LIST_API_URL)\n    .then((responseData) =\u003e {\n      dispatch(getList(responseData.list))\n    })\n    .catch((error) =\u003e {\n      console.log(error.message)\n    })\n  }\n}\n\nconst getList = (payload) =\u003e {\n  return {\n    type: \"GET_LIST\",\n    payload\n  }\n}\n\nexport { fetchList }\n```\n\n**2. Redux Saga:**\n\nRedux Saga leverages an `ES6` feature called `Generators`, allowing us to write asynchronous code that looks synchronous, and is very easy to test. In the saga, we can test our asynchronous flows easily and our actions stay pure. It organized complicated asynchronous actions easily and make then very readable and the saga has many useful tools to deal with asynchronous actions.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-saga.png\" alt=\"Redux Saga\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n**Example:**\n\n```js\nimport axios from \"axios\"\nimport GET_LIST_API_URL from \"../config\"\nimport {call, put} from \"redux-saga/effects\"\n\nconst fetchList = () =\u003e {\n  return axios.get(GET_LIST_API_URL)\n}\n\nfunction *fetchList () {\n  try {\n    const responseData = yield call(getCharacters)\n    yield put({type: \"GET_LIST\", payload: responseData.list})\n  } catch (error) {\n    console.log(error.message)\n  }\n}\n\nexport { fetchList }\n```\n\nBoth Redux Thunk and Redux Saga take care of dealing with side effects. In very simple terms, applied to the most common scenario (async functions, specifically AJAX calls) Thunk allows Promises\" to deal with them, Saga uses Generators. Thunk is simple to use and Promises are familiar to many developers, Saga/Generators are more powerful but you will need to learn them. When Promises are just good enough, so is Thunk, when you deal with more complex cases on a regular basis, Saga gives you better tools.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make Ajax request in Redux?\n\nThere are three most widely used and stable Redux Ajax middleware are:\n\n* Redux Promise Middleware\n* Redux Thunk Middleware\n* Redux Saga Middleware\n\n**1. Redux Promise Middleware:**\n\nThis is the most simple way of doing Ajax calls with Redux. When using Redux Promise, your action creator can return a Promise inside the Action.\n\n```js\nfunction getUserName(userId) {\n    return {\n        type: \"SET_USERNAME\",\n        payload: fetch(`/api/personalDetails/${userId}`)\n                .then(response =\u003e response.json())\n                .then(json =\u003e  json.userName)\n    }\n}\n```\n\nThis middleware automatically dispatches two events when the Ajax call succeeds: `SETUSERNAMEPENDING`  and `SETUSERNAMEFULFILLED`. If something fails it dispatches `SETUSERNAMEREJECTED`.\n\n**When to use:**\n\n* You want the simplest thing with minimum overhead\n* You prefer convention over configuration\n* You have simple Ajax requirements\n\n**2. Redux Thunk Middleware:**\n\nThis is the standard way of doing Ajax with Redux. When using Redux Thunk, your action creators returns a function that takes one argument dispatch:\n\n```js\nfunction getUserName(userId) {\n    return dispatch =\u003e {\n        return fetch(`/api/personalDetails/${userId}`)\n        .then(response =\u003e response.json())\n        .then(json =\u003e dispatch({ type: \"SET_USERNAME\", userName: json.userName })\n    }\n}\n```\n\nThe action creator can call dispatch inside `.then` to execute it asynchronously. The action creator can call dispatch as many time as it wants.\n\n**When to use:**\n\n* You make many Ajax calls in one action, and need to dispatch many actions\n* You require full control of the format of your actions\n\n**3. Redux Saga Middleware:**\n\nThis is the most advanced way of doing Ajax with Redux. It uses an ES6 feature called `generators`. When using Redux Saga you do your Ajax calls in a saga instead of an action creator. This is how a saga looks like:\n\n```js\nimport { call, put, takeEvery } from 'redux-saga/effects'\n\n// call getUserName when action SET_USERNAME is dispatched\nfunction* mySaga() {\n  yield takeEvery(\"SET_USERNAME\", getUserName);\n}\n\nfunction* getUserName(action) {\n   try {\n      const user = yield call(fetch, `/api/personalDetails/${userId}`);\n      yield put({type: \"SET_USERNAME_SUCCEEDED\", user: user});\n   } catch (e) {\n      yield put({type: \"SET_USERNAME_FAILED\", message: e.message});\n   }\n}\n\nexport default mySaga\n```\n\nHere, sagas listen to actions which you dispatch as regular synchronous actions. In this case, the saga `getUserName` is executed when the action `SET_USERNAME` is dispatched. The `*` next to the function means it\\'s a generator and yield is a generator keyword.\n\n**When to use:**\n\n* You need to be able to test the asynchronous flow easily\n* You are comfortable working with ES6 Generators\n* You value pure functions\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the differences between call and put in redux-saga?\n\nBoth `call()` and `put()` are effect creator functions. `call()` function is used to create effect description, which instructs middleware to call the promise. `put()` function creates an effect, which instructs middleware to dispatch an action to the store.\n\nLet\\'s take example of how these effects work for fetching particular user data.\n\n```js\nfunction* fetchUserSaga(action) {\n  // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.\n  // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable\n  const userData = yield call(api.fetchUser, action.userId)\n \n  // Instructing middleware to dispatch corresponding action.\n  yield put({\n    type: 'FETCH_USER_SUCCESS',\n    userData\n  })\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the mental model of redux-saga?\n\nSaga is like a separate thread in your application, that is solely responsible for side effects. `redux-saga` is a redux middleware, which means this thread can be **started**, **paused** and **cancelled** from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.\n\n**Example:**\n\n```bash\nnpm install --save redux-saga\n```\n\nSuppose we have a UI to fetch some user data from a remote server when a button is clicked.\n\n```js\nclass UserComponent extends React.Component {\n  ...\n  onSomeButtonClicked() {\n    const { userId, dispatch } = this.props\n    dispatch({type: 'USER_FETCH_REQUESTED', payload: {userId}})\n  }\n  ...\n}\n```\n\nThe Component dispatches a plain Object action to the Store. We\\'ll create a Saga that watches for all `USER_FETCH_REQUESTED` actions and triggers an API call to fetch the user data.\n\n```js\n// sagas.js\n\nimport { call, put, takeEvery, takeLatest } from 'redux-saga/effects'\nimport Api from '...'\n\n// worker Saga: will be fired on USER_FETCH_REQUESTED actions\nfunction* fetchUser(action) {\n   try {\n      const user = yield call(Api.fetchUser, action.payload.userId);\n      yield put({type: \"USER_FETCH_SUCCEEDED\", user: user});\n   } catch (e) {\n      yield put({type: \"USER_FETCH_FAILED\", message: e.message});\n   }\n}\n\n/*\n  Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.\n  Allows concurrent fetches of user.\n*/\nfunction* mySaga() {\n  yield takeEvery(\"USER_FETCH_REQUESTED\", fetchUser);\n}\n\n/*\n  Alternatively you may use takeLatest.\n\n  Does not allow concurrent fetches of user. If \"USER_FETCH_REQUESTED\" gets\n  dispatched while a fetch is already pending, that pending fetch is cancelled\n  and only the latest one will be run.\n*/\nfunction* mySaga() {\n  yield takeLatest(\"USER_FETCH_REQUESTED\", fetchUser);\n}\n\nexport default mySaga;\n```\n\nTo run our Saga, we\\'ll have to connect it to the Redux Store using the `redux-saga` middleware.\n\n```js\n// main.js\n\nimport { createStore, applyMiddleware } from 'redux'\nimport createSagaMiddleware from 'redux-saga'\n\nimport reducer from './reducers'\nimport mySaga from './sagas'\n\n// create the saga middleware\nconst sagaMiddleware = createSagaMiddleware()\n// mount it on the Store\nconst store = createStore(\n  reducer,\n  applyMiddleware(sagaMiddleware)\n)\n\n// then run the saga\nsagaMiddleware.run(mySaga)\n\n// render the application\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 8. REDUX FORMS\n\n\u003cbr/\u003e\n\n## Q. Explain Redux form with an example?\n\nThis is a simple demonstration of how to connect all the standard HTML form elements to redux-form.\n\nFor the most part, it is a matter of wrapping each form control in a `\u003cField\u003e` component, specifying which type of `React.DOM` component you wish to be rendered.\n\nThe Field component will provide your input with `onChange`, `onBlur`, `onFocus`, `onDrag`, and `onDrop` props to listen to the events, as well as a **value** prop to make each input a **controlled component**. Notice that the SimpleForm component has no state; in fact, it uses the functional stateless component syntax.\n\n**Example:**\n\n```js\n// SimpleForm.js\n\nimport React from 'react'\nimport { Field, reduxForm } from 'redux-form'\n\nconst SimpleForm = (props) =\u003e {\n  const { handleSubmit, pristine, reset, submitting } = props\n  return (\n    \u003cform onSubmit={handleSubmit}\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eName\u003c/label\u003e\n        \u003cdiv\u003e\n          \u003cField name=\"name\" component=\"input\" type=\"text\" placeholder=\"Name\"/\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eSex\u003c/label\u003e\n        \u003cdiv\u003e\n          \u003clabel\u003e\u003cField name=\"sex\" component=\"input\" type=\"radio\" value=\"male\"/\u003e Male\u003c/label\u003e\n          \u003clabel\u003e\u003cField name=\"sex\" component=\"input\" type=\"radio\" value=\"female\"/\u003e Female\u003c/label\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eFavorite Color\u003c/label\u003e\n        \u003cdiv\u003e\n          \u003cField name=\"favoriteColor\" component=\"select\"\u003e\n            \u003coption\u003e\u003c/option\u003e\n            \u003coption value=\"ff0000\"\u003eRed\u003c/option\u003e\n            \u003coption value=\"00ff00\"\u003eGreen\u003c/option\u003e\n            \u003coption value=\"0000ff\"\u003eBlue\u003c/option\u003e\n          \u003c/Field\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n      \u003cdiv\u003e\n        \u003cbutton type=\"submit\" disabled={pristine || submitting}\u003eSubmit\u003c/button\u003e\n        \u003cbutton type=\"button\" disabled={pristine || submitting} onClick={reset}\u003eClear\u003c/button\u003e\n      \u003c/div\u003e\n    \u003c/form\u003e\n  )\n}\n\nexport default reduxForm({\n  form: 'simple'  // a unique identifier for this form\n})(SimpleForm)\n```\n\n**Reference:**\n\n* *[https://redux-form.com/6.5.0/examples/syncvalidation/](https://redux-form.com/6.5.0/examples/syncvalidation/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Redux Form initialValues get updated from state?\n\nAdd `enableReinitialize : true` When set to true, the **form** will reinitialize every time the initialValues prop changes\n\n```js\n...\n\nexport default connect(mapStateToProps)(reduxForm({ \n  form: 'contactForm', \n  enableReinitialize: true\n})(ContactForm))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 9. REDUX MISCELLANEOUS\n\n\u003cbr/\u003e\n\n## Q. What is redux toolkit?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the at symbol in the Redux connect decorator?\n\nDecorators make it possible to annotate and modify classes and properties at design time.\n\nHere\\'s an example of setting up Redux without and with a decorator:\n\n**Without a decorator:**\n\n```js\nimport React from 'react'\nimport * as actionCreators from './actionCreators'\nimport { bindActionCreators } from 'redux'\nimport { connect } from 'react-redux'\n\nfunction mapStateToProps(state) {\n  return { todos: state.todos }\n}\n\nfunction mapDispatchToProps(dispatch) {\n  return { actions: bindActionCreators(actionCreators, dispatch) }\n}\n\nclass MyApp extends React.Component {\n  // ...define your main app here\n}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(MyApp)\n```\n\n**Using a decorator:**\n\n```js\nimport React from 'react'\nimport * as actionCreators from './actionCreators'\nimport { bindActionCreators } from 'redux'\nimport { connect } from 'react-redux'\n\nfunction mapStateToProps(state) {\n  return { todos: state.todos }\n}\n\nfunction mapDispatchToProps(dispatch) {\n  return { actions: bindActionCreators(actionCreators, dispatch) }\n}\n\n@connect(mapStateToProps, mapDispatchToProps)\nexport default class MyApp extends React.Component {\n  // ...define your main app here\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between React State vs Redux State?\n\nReact state is stored locally within a component. When it needs to be shared with other components, it is passed down through props. In practice, this means that the top-most component in your app needing access to a mutable value will hold that value in its state. If it can be mutated by subcomponents, you must pass a callback to handle the change into subcomponents.\n\nWhen using Redux, state is stored globally in the Redux store. Any component that needs access to a value may subscribe to the store and gain access to that value. Typically, this is done using container components. This centralizes all data but makes it very easy for a component to get the state it needs, without surrounding components knowing of its needs.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Flux?\n\nFlux is an application design paradigm used as a replacement for the more traditional MVC pattern. Flux is a Javascript architecture or pattern for UI which runs on a unidirectional data flow and has a centralized dispatcher. It is useful when your project has dynamic data and you need to keep the data updated in an effective manner. It was created by Facebook, and complements React as view.\n\n**Architecture:**\n\nThe Flux architecture is based on the following components:\n\n* **Store/ Stores**: Serves as a container for the app state \u0026 logic\n* **Action**: Enables data passing to the dispatcher\n* **View**: Same as the view in MVC architecture, but in the context of React components\n* **Dispatcher**: Coordinates actions \u0026 updates to stores\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/flux-architecture.png\" alt=\"Flux Architecture\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nIn the Flux architecture, when a user clicks on something, the view creates actions. Action can create new data and send it to the dispatcher. The dispatcher then dispatches the action result to the appropriate store. The store updates the state based on the result and sends an update to the view.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the drawbacks of Redux contrasted with Flux?\n\n**Flux vs Redux:**\n\n| Flux                                       | Redux                            |\n|--------------------------------------------|----------------------------------|\n|Follows the unidirectional flow             |Follows the unidirectional flow   |\n|Includes multiple stores                    |Includes single store             |\n|Store handles all logic                     |Reducer handles all logic         |\n|Ensures simple debugging with the dispatcher|Single store makes debugging lot easier|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Describe Flux vs MVC?\n\n**1. MVC:**\n\nMVC stands for Model View Controller. It is an architectural pattern used for developing the user interface. It divides the application into three different logical components: the Model, the View, and the Controller.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/mvc.png\" alt=\"MVC\" /\u003e\n\u003c/p\u003e\n\n* **Model**: It is responsible for maintaining the behavior and data of an application.\n* **View**: It is used to display the model in the user interface.\n* **Controller**: It acts as an interface between the Model and the View components. It takes user input, manipulates the data(model) and causes the view to update.\n\nMVC can be interpreted or modified in many ways to fit a particular framework or library. The core ideas of MVC can be formulated as:\n\n* Separating the presentation from the model: enables implementation of different UIs and better testability\n* Separating the controller from the view: most useful with web interfaces and not commonly used in most GUI frameworks\n\nIn general, MVC makes no assumptions about whether data flow within an application should be unidirectional or bidirectional. In server Side, MVC is good, but in Client side most of the JS frameworks provide data binding support which let the view can talk with model directly, It shoudn\\'t be, Many times it become hard to debug something as there are scope for a property being changed by many ways.\n\n**2. Flux:**\n\nFlux places unidirectional data flow front and center, by making it a requirement. Here are the four major roles that make up the Flux architecture:\n\n* Actions, which are helper methods that relay information to the dispatcher\n* Stores are similar to the models in MVC, except they act as containers for application state and logic for a particular domain within the application\n* The Dispatcher receives Actions and acts as the sole registry of callbacks to all stores within an application. It also manages the dependencies between stores\n* Views are the same as the view in MVC, except in the context of React and Flux, and also include Controller-Views for change events and retrieve application state from stores as required.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/flux-2.png\" alt=\"Flux\" width=\"600px\" /\u003e\n\u003c/p\u003e\n\n1. All data in the application flow through a central hub called the Dispatcher\n2. This data is tracked as actions, which are provided to the dispatcher in an action creator method, often as a result of a user interacting with the view\n3. The dispatcher invokes the registered callback, effectively dispatching the action to all stores that have registered with that callback\n4. The stores in turn relay that change event to the controller-views to alert them of the change\n5. The controller-views listen for events, retrieve data from the appropriate stores as required and re-render themselves and all their children in the component tree accordingly.\n\n**MVC vs Flux:**\n\n|  MVC                   |Flux                              |\n|------------------------|----------------------------------|\n|Bidirectional data flow |Unidirectional data flow          |\n|Data binding is the key |Events or actions are the main players |\n|Controllers handle the business logic | Store does all calculations |\n|Somewhat synchronous    |Can be implemented as completely asynchronous |\n|It is hard to debug.    |It is easy to debug because it has common initiating point: Dispatcher.|\n|Its maintainability is difficult as the project scope goes huge. | Its maintainability is easy and reduces runtime errors.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to add multiple middleware to redux?\n\nThe most common use case for middleware is to support asynchronous actions without much boilerplate code or a dependency on a library like `RxJS`. It does so by letting you dispatch async actions in addition to normal actions.\n\n`applyMiddleware` takes each piece of middleware as a new argument (not an array). It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. It can be use for logging, crash reporting, talking to an asynchronous API, routing, and more.\n\n```js\nconst createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore);\n```\n\n**Example: Custom Logger Middleware:**\n\n```js\nimport { createStore, applyMiddleware } from 'redux'\nimport todos from './reducers'\n\nfunction logger({ getState }) {\n  return next =\u003e action =\u003e {\n    console.log('will dispatch', action)\n\n    // Call the next dispatch method in the middleware chain.\n    const returnValue = next(action)\n\n    console.log('state after dispatch', getState())\n\n    // This will likely be the action itself, unless\n    // a middleware further in chain changed it.\n    return returnValue\n  }\n}\n\nconst store = createStore(todos, ['Use Redux'], applyMiddleware(logger))\n\nstore.dispatch({\n  type: 'ADD_TODO',\n  text: 'Understand the middleware'\n})\n// (These lines will be logged by the middleware:)\n// will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }\n// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set initial state in Redux?\n\n**1. Initializing State:**\n\nIn Redux, all application state is held in the store; which is an object that holds the complete state tree of your app. There is only one way to change its state and that is by dispatching actions.\n\nActions are objects that consist of a type and a payload property. They are created and dispatched by special functions called action creators.\n\n*Example: First creating the Redux store*\n\n```js\nimport { createStore } from 'redux'\n\nfunction todosReducer(state = [], action) {\n  switch (action.type) {\n    case 'ADD_TODO':\n      return state.concat([action.payload])\n    default:\n      return state\n  }\n}\n\nconst store = createStore(todosReducer)\n```\n\nNext updating the store\n\n```js\nconst ADD_TODO = add_todo; // creates the action type\nconst newTodo = [\"blog on dev.to\"];\nfunction todoActionCreator (newTodo) {\n  const action = {\n    type: ADD_TODO,\n    payload: newTodo\n  }\n  dispatch(action)\n}\n```\n\nWhen a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state.\n\n**2. createStore Pattern:**\n\nThe createStore method can accept an optional preloadedState value as its second argument. In our example, we called `createStore()` without passing this value. When a value is passed to the `preloadedState` it becomes the initial state.\n\n```js\nconst initialState = [\"eat\", \"code\", \"sleep\"];\nconst store = createStore(todosReducer, initialState)\n```\n\n**3. Reducer Pattern:**\n\nReducers can also specify an initial state value by looking for an incoming state argument that is undefined, and returning the value they'd like to use as a default.\n\n```js\nfunction todosReducer(state = [], action) {\n  switch (action.type) {\n    case 'ADD_TODO':\n      return state.concat([action.payload])\n    default:\n      return state\n  }\n}\n/**\n* sets initial state to []. But would only take effect if the initial state is undefined,\n* which means it was not set using createStore().\n**/\n```\n\nIn general, `preloadedState` wins over the state specified by the `reducer`. This lets reducers specify initial data that makes sense to them as default arguments, but also allows loading existing data (fully or partially) when you\\'re hydrating the store from some persistent storage or the server.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of the constants in Redux?\n\n* It helps keep the naming consistent because all action types are gathered in a single place.\n* Sometimes you want to see all existing actions before working on a new feature. It may be that the action you need was already added by somebody on the team, but you didn\\'t know.\n* The list of action types that were added, removed, and changed in a Pull Request helps everyone on the team keep track of scope and implementation of new features.\n* If you make a typo when importing an action constant, you will get undefined. This is much easier to notice than a typo when you wonder why nothing happens when the action is dispatched.\n\n**Example:** Constants in Redux can be used into two places, reducers and during actions creation.\n\n```js\n// actionTypes.js\n\nexport const ADD_TODO = 'ADD_TODO'\nexport const DELETE_TODO = 'DELETE_TODO'\nexport const EDIT_TODO = 'EDIT_TODO'\nexport const COMPLETE_TODO = 'COMPLETE_TODO'\nexport const COMPLETE_ALL = 'COMPLETE_ALL'\nexport const CLEAR_COMPLETED = 'CLEAR_COMPLETED'\n```\n\nAnd then require it in actions creator file\n\n```js\n// actions.js\n\nimport { ADD_TODO } from './actionTypes'\n\nexport function addTodo(text) {\n  return { type: ADD_TODO, text }\n}\n```\n\nAnd in some reducer\n\n```js\nimport { ADD_TODO } from './actionTypes'\n\nexport default (state = [], action) =\u003e {\n  switch (action.type) {\n    case ADD_TODO:\n      return [\n        ...state,\n        {\n          text: action.text,\n          completed: false\n        }\n      ]\n    default:\n      return state\n  }\n}\n```\n\nIt allows to easily find all usages of that constant across the project. It also prevents from introducing silly bugs caused by typos -- in which case, you will get a `ReferenceError` immediately.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between React context and React Redux?\n\n**React Context:**\n\nContext provides a way to pass data through the component tree without having to pass props down manually at every level.\n\nIn a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.\n\n**Redux:**\n\nRedux is a pattern and library for managing and updating application state, using events called \"actions\". It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.\n\nRedux helps you manage \"global\" state - state that is needed across many parts of your application.\n\nThe patterns and tools provided by Redux make it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur.\n\n**Redux vs Context API**\n\n**1.) Implementation**\n\nContext API is easy to is use as it has a short learning curve. It requires less code, and because there\\'s no need of extra libraries, bundle sizes are reduced. Redux on the other hand requires adding more libraries to the application bundle. The syntax is complex and extensive creating unnecessary work and complexity. However, it\\'s still a great alternative regarding prop drilling.\n\n**2.) Rendering**\n\nContext API prompts a re-render on each update of the state and re-renders all components regardless. Redux however, only re-renders the updated components. \n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to reset state in redux?\n\nThe root reducer would normally delegate handling the action to the reducer generated by `combineReducers()`. However, whenever it receives `USER_LOGOUT` action, it returns the initial state all over again.\n\n```js\nimport { combineReducers } from 'redux';\nimport AppReducer from './AppReducer';\n\nimport UsersReducer from './UsersReducer';\nimport OrderReducer from './OrderReducer';\nimport NotificationReducer from './NotificationReducer';\nimport CommentReducer from './CommentReducer';\n\n/**\n * In order to reset all reducers back to their initial states when user logout,\n * rewrite rootReducer to assign 'undefined' to state when logout\n *\n * If state passed to reducer is 'undefined', then the next state reducer returns\n * will be its initial state instead; since we have assigned it as the default value\n * of reducer's state parameter\n *   ex: const Reducer = (state = InitialState, action) =\u003e { ... }\n *\n * See: https://goo.gl/GSJ98M and combineReducers() source codes for details\n */\n\nconst appReducer = combineReducers({\n  /* your app's top-level reducers */\n  users: UsersReducer,\n  orders: OrderReducer,\n  notifications: NotificationReducer,\n  comment: CommentReducer,\n});\n\nconst rootReducer = (state, action) =\u003e {\n  // when a logout action is dispatched it will reset redux state\n  if (action.type === 'USER_LOGGED_OUT') {\n    state = undefined;\n  }\n\n  return appReducer(state, action);\n}\n\nexport default rootReducer\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why are Redux state functions called as reducers?\n\nRedux state functions called a reducer because it\\'s the type of function we pass to `Array.prototype.reduce(reducer, ?initialValue)`. Reducers do not just return default values. They always return the accumulation of the state (based on all previous and current actions).\n\nTherefore, they act as a reducer of state. Each time a redux reducer is called, the state is passed in with the action `(state, action)`. This state is then reduced (or accumulated) based on the action, and then the next state is returned. This is one cycle of the classic `fold` or `reduce` function.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Relay?\n\nRelay is a JavaScript framework for fetching and managing GraphQL data in React applications that emphasizes maintainability, type safety and runtime performance.\n\nRelay achieves this by combining declarative data fetching and a static build step. With declarative data fetching, components declare what data they need, and Relay figures out how to efficiently fetch it. During the static build step, Relay validates and optimizes queries, and pre-computes artifacts to achieve faster runtime performance.\n\n**Reference:**\n\n* *[https://relay.dev/docs/](https://relay.dev/docs/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Relay is different from Redux?\n\n**Redux**\n\nPredictable state container for JavaScript apps. Redux helps you write applications that behave consistently, run in different environments (client, server, and native). In redux the application state is located in a single store, each component can access the state, and can also change the state by dispatching actions. Redux doesn\\'t handle data fetching out of the box, though it can be done manually: simply create an action that fetches the data from the server into the store.\n\nSome of the features offered by Redux are:\n\n* Predictable state\n* Easy testing\n* Works with other view layers besides React\n\n**Relay**\n\nCreated by facebook for react, and also used internally there. Relay is similar to redux in that they both use a single store. The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL querys (for reading data) and mutations (for changing data). Relay caches the data for you and optimizes data fetching for you, by fetching only changed data and nothing more. Relay also supports optimistic updates, i.e. changing the state before the server\\'s result arrives.\n\nRelay provides the following key features:\n\n* Build data driven apps\n* Declarative style\n* Mutate data on the client and server\n\n**GraphQL** is a web service framework and protocol using declarative and composable queries, and solves problem like over fetching and under fetching, it is believed to be a valid candidate to replace REST.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When would bindActionCreators be used in react/redux?\n\n**`bindActionCreators(actionCreators, dispatch)`**: Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly.\n\nWhen we use Redux with React, react-redux will provide `dispatch()` function and we can call it directly. The only use case for `bindActionCreators()` is when we want to pass some action creators down to a component that isn\\'t aware of Redux, and we don\\'t want to pass `dispatch` or the Redux store to it.\n\n**Parameters**\n\n1. `actionCreators` (Function or Object): An action creator, or an object whose values are action creators.\n2. `dispatch` (Function): A dispatch function available on the Store instance.\n\n**Returns**\n\n(Function or Object): An object mimicking the original object, but with each function immediately dispatching the action returned by the corresponding action creator. If you passed a function as actionCreators, the return value will also be a single function.\n\n**Example:**\n\n```js\n// TodoActionCreators.js\n\nexport function addTodo(text) {\n  return {\n    type: 'ADD_TODO',\n    text\n  }\n}\n\nexport function removeTodo(id) {\n  return {\n    type: 'REMOVE_TODO',\n    id\n  }\n}\n```\n\n```js\n// TodoListContainer.js\n\nimport { Component } from 'react'\nimport { bindActionCreators } from 'redux'\nimport { connect } from 'react-redux'\n\nimport * as TodoActionCreators from './TodoActionCreators'\n\nconsole.log(TodoActionCreators)\n// {\n//   addTodo: Function,\n//   removeTodo: Function\n// }\n\nclass TodoListContainer extends Component {\n  constructor(props) {\n    super(props)\n\n    const { dispatch } = props\n\n    // Here's a good use case for bindActionCreators:\n    // You want a child component to be completely unaware of Redux.\n    // We create bound versions of these functions now so we can\n    // pass them down to our child later.\n\n    this.boundActionCreators = bindActionCreators(TodoActionCreators, dispatch)\n    console.log(this.boundActionCreators)\n    // {\n    //   addTodo: Function,\n    //   removeTodo: Function\n    // }\n  }\n\n  componentDidMount() {\n    // Injected by react-redux:\n    let { dispatch } = this.props\n\n    // Note: this won't work:\n    // TodoActionCreators.addTodo('Use Redux')\n\n    // You're just calling a function that creates an action.\n    // You must dispatch the action, too!\n\n    // This will work:\n    let action = TodoActionCreators.addTodo('Use Redux')\n    dispatch(action)\n  }\n\n  render() {\n    // Injected by react-redux:\n    let { todos } = this.props\n\n    return \u003cTodoList todos={todos} {...this.boundActionCreators} /\u003e\n\n    // An alternative to bindActionCreators is to pass\n    // just the dispatch function down, but then your child component\n    // needs to import action creators and know about them.\n\n    // return \u003cTodoList todos={todos} dispatch={dispatch} /\u003e\n  }\n}\n\nexport default connect(state =\u003e ({ todos: state.todos }))(TodoListContainer)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is mapStateToProps and mapDispatchToProps?\n\n`react-redux`package provides 3 functions `Connect`, `mapStapteToProps` and `mapDispatchToProps`. Connect is a higher order function that takes in both mapStateToProps and mapDispatchToProps as parameters.\n\n**1. Using MapStateToProps**\n\nIn React, `MapStatetoProps` pulls in the state of a specific reducer state object from global store and maps it to the props of component. MapStateToProps is called everytime your store is updated. You pass in your state a retrieve that specific objects from the reducer.\n\n**2. Using MapDisptachToProps**\n\n`MapDispatchToProp` takes the dispatch functions in component and executes them against the Redux Reducer when that function is fired. MapDispatchToProps allows to dispatch state changes to your store.\n\nIn a simple term,\n\n**mapStateToProps**: It connects redux state to props of react component.  \n**mapDispatchToProps**: It connects redux actions to react props.\n\n**Example:**\n\n```js\nconst {createStore} = Redux\nconst {connect, Provider} = ReactRedux\nconst InitialState = {Collection: [\"COW\", \"COW\", \"DUCK\", \"DUCK\"]}\n\nfunction reducer(state=InitialState, action) {\n    if (action.type === \"REVERSE\") {\n      return Object.assign({}, state, {\n         Collection: state.Collection.slice().reverse()\n      })\n    }\n    return state\n}\n\nvar store = createStore(reducer)\n\nfunction mapStateToProps(state) {\n  return state\n}\n\nvar PresentationalComponent = React.createClass({\n    render: function() {\n        return (\n          \u003cdiv\u003e\n            \u003ch2\u003eStore State ( as Props) \u003c/h2\u003e\n            \u003cpre\u003e {JSON.stringify(this.props.Collection)}\u003c/pre\u003e\n            \u003cStateChangerUI /\u003e\n          \u003c/div\u003e\n          )\n    }\n})\n\n// State changer UI\nvar StateChangerUI = React.createClass({\n // Action Dispatch  \n  handleClick: function() {\n     store.dispatch({\n         type: 'REVERSE'\n      })\n  },\n  render: function() {\n    return (\n      \u003cbutton type=\"button\" className=\"btn btn-success\" onClick={this.handleClick}\u003eREVERSE\u003c/button\u003e\n    )\n  }\n})\n\nPresentationalComponent = connect(mapStateToProps)(PresentationalComponent)\n\nReactDOM.render(\n    \u003cProvider store={store}\u003e\n        \u003cPresentationalComponent /\u003e\n    \u003c/Provider\u003e,\n    document.getElementById('App')\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the different ways to write mapDispatchToProps()?\n\n**mapDispatchToProps** is the second argument that connect expects to receive. In the context of a react-redux application, the `mapDispatchToProps` argument is responsible for enabling a component to dispatch actions. \n\nIn practical terms, `mapDispatchToProps` is where react events (and lifecycle events) are mapped to redux actions. There are a few ways of binding action creators to `dispatch()` in `mapDispatchToProps()`.\n\n```js\nconst mapDispatchToProps = (dispatch) =\u003e ({\n action: () =\u003e dispatch(action())\n})\n\n// shorthand way\nconst mapDispatchToProps = { action }\n```\n\n```js\nconst mapDispatchToProps = (dispatch) =\u003e ({\n action: bindActionCreators(action, dispatch)\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?\n\n**mapStateToProps:**\n\n```js\nfunction mapStateToProps(state, ownProps?)\n```\n\nIt should take a first argument called `state`, optionally a second argument called `ownProps`, and return a plain object containing the data that the connected component needs.\n\nThis function should be passed as the first argument to connect, and will be called every time when the Redux store state changes. If you do not wish to subscribe to the store, pass `null` or `undefined` to connect in place of `mapStateToProps`.\n\n**Arguments**\n\n* state\n* ownProps (optional)\n\n**State:**\n\nThe first argument to a `mapStateToProps` function is the entire Redux store state.\n\n**Example:**\n\n```js\n// Employee.js\n\nfunction mapStateToProps(state) {\n  const { emp } = state\n  return { empList: emp.allIds }\n}\n\nexport default connect(mapStateToProps)(EmpList)\n```\n\n**ownProps (optional):**\n\nIf your component needs the data from its own props to retrieve data from the store. This argument will contain all of the props given to the wrapper component that was generated by connect.\n\n**Example:**\n\n```js\n// Employee.js\n\nfunction mapStateToProps(state, ownProps) {\n  const { visibilityFilter } = state\n  // ownProps would look like { \"id\" : 100 }\n  const { id } = ownProps\n  const emp = getEmployeeById(state, id)\n\n  // component receives additionally:\n  return { emp, visibilityFilter }\n}\n\n// Later, in your application, a parent component renders:\n;\u003cConnectedEmployee id={100} /\u003e\n// and your component receives props.id, props.emp, and props.visibilityFilter\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is reselect and how it works?\n\n**`Reselect`** is a simple library for creating memoized, composable **selector** functions. Reselect selectors can be used to efficiently compute derived data from the Redux store.\n\nSelectors can compute derived data, allowing Redux to store the minimal possible state. Which can be considered as keep the store as minimal as possible. A selector is not recomputed unless one of its arguments change. A memoized selector that recalculates only when that part of the start tree changes which are input arguments to the selector. The value of selector doesn\\'t change when there is no change in other (unrelated) parts of the state tree.\n\n**selectors**\n\nIn our context, selectors are nothing but functions which can compute or retrive data from the store. We usually fetch the state data using `mapStateToProps()` function like this.\n\n```js\nconst mapStateToProps = (state) =\u003e {\n  return {\n    activeData: getActiveData(state.someData, state.isActive)\n  }\n}\n```\n\nWhere `getActiveData()` will be a function which returns all the records from `someData` having the status as `isActive`. The drawback with this function is, whenever any part of the state state updates, this function will recalculate this data.\n\nWhen we use `Reselect` it caches the input arguments to the memoized function. So only when the arguments of the function changes from the previous call, the selector recalculates.\n\n**Example:**\n\n```js\n// todo.reducer.js\n// ...\nimport { createSelector } from 'reselect';\n\nconst todoSelector = state =\u003e state.todo.todos;\nconst searchTermSelector = state =\u003e state.todo.searchTerm;\n\nexport const filteredTodos = createSelector(\n  [todoSelector, searchTermSelector],\n  (todos, searchTerm) =\u003e {\n    return todos.filter(todo =\u003e todo.title.match(new RegExp(searchTerm, 'i')));\n  }\n);\n\n// ...\n```\n\nWe can use the `filteredTodos` selectors to get all the todos if there\\'s no searchTerm set in the state, or a filtered list otherwise.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the different ways to dispatch actions in Redux?\n\n**Redux** is a state container for Javascript apps, mostly used with React. It\\'s based on actions that are dispatched and listened by reducers which modify the state properly.\n\n**1. Passing dispatch method to component**\n\nThe dispatch method is a method of the store object. An action is dispatched to trigger an update to the store.\n\n```js\n// App.js\nimport { createStore } from 'redux';\nimport { MessageSender } from './MessageSender';\nimport reducer from './reducer';\n\nconst store = createStore(reducer);\nclass App extends React.Component {\n render() {\n \u003cMessageSender store={store} /\u003e\n };\n};\n```\n\n```js\n// MessageSender.js\nimport { sendMsg } from './actions';\n// ...\nthis.props.store.dispatch(sendMsg(msg))\n// ...\n```\n\n**2. Using React-Redux to make dumb/smart components**\n\nThe downside of the above approach is that our React component is aware of the app logic. It\\'s best to separate the logic in our smart component connected to the store from the user interface, i.e., from the dumb component.\n\nFrom the official docs for `connect()`, we can describe `mapDispatchToProps()` this way: If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component\\'s props.\n\n```js\n// MessageSender.container.js\n\nimport { connect } from 'react-redux';\nimport { sendMsg } from './actions';\nimport MessageSender from './MessageSender';\n\nconst mapDispatchToProps = {\n sendMsg\n};\n\nexport default connect(null, mapDispatchToProps)(MessageSender);\n\n// MessageSender.js\n// ...\nthis.props.sendMsg(msg);\n// ...\n```\n\n**3. Using the bindActionCreators() method**\n\nThe `bindActionCreators()` method allows us to dispatch actions from any React component that is not connected to the store as `mapDispatchToPros()` in the connect function of react-redux.\n\n```js\n// MsgSenderPage.js\n\nimport { bindActionCreators } from 'redux';\nimport { connect } from 'react-redux';\nimport * as actions from './actions';\n\nclass MsgSenderPage extends React.Component {\n constructor(props) {\n super(props);\n const { dispatch } = props;\n this.boundedActions = bindActionCreators(actions, dispatch);\n }\n\n render() {\n return \u003cMsgSending {...this.boundedActions} /\u003e;\n }\n}\n\nexport default connect()(MsgSenderPage);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are Redux selectors and Why to use them?\n\nA **selector** is simply a function that accepts Redux state as an argument and returns data that is derived from that state.\n\nSelectors help to keep your Redux store state minimal and derive data from the state as needed. They can compute derived data, allowing Redux to store the minimal possible state. Selectors are also very efficient. A selector is not recomputed unless one of its arguments changes.\n\n**Example:** \n\n```js\n// Arrow function, direct lookup\nconst selectEntities = state =\u003e state.entities\n\n// Function declaration, mapping over an array to derive values\nfunction selectItemIds(state) {\n  return state.items.map(item =\u003e item.id)\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is reselect and how it works?\n\n**Reselect** is a selector library (for Redux) for building memoized selectors. Using memoization, we can prevent unnecessary rerenders and recalculations of derived data which in turn will speed up our application.\n\nReselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the the same inputs are provided twice in a row, Reselect returns the cached output. It\\'s memoization and cache are fully customizable.\n\n**Example:** Let\\'s look at a simple selector using Reselect\n\n```js\nimport { createselectetor } from 'reselect'\n\nexport const getItems = (state) =\u003e state.cart.get('items');\n\nexport const getItemsWithTotals = createSelector(\n  [getItems],\n  (items) =\u003e {\n    return items.map(i =\u003e {\n      return i.set('total', i.get('price', 0) * i.get('quantity'));\n    });\n  }\n);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Can I dispatch an action in reducer?\n\nDispatching an action within a reducer is an **anti-pattern**. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Redux DevTools?\n\nRedux-Devtools provide us debugging platform for Redux apps. It allows us to perform time-travel debugging and live editing with hot reloading, action replay, and customizable UI.\n\nSome of the features in official documentation are as follows −\n\n* It allows you inspect every state and action payload.\n* It allows you go back in time by \"cancelling\" actions.\n* If you change the reducer code, each \"staged\" action will be re-evaluated.\n* If the reducers throw, we can identify the error and also during which action this happened.\n* With `persistState()` store enhancer, you can persist debug sessions across page reloads.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/redux-devtool.png\" alt=\"Redux DevTool\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**Reference:**\n\n* *[https://github.com/reduxjs/redux-devtools](https://github.com/reduxjs/redux-devtools)*\n\n## Q. How to set conditional action on state in React-redux\n\nActions are plain objects that send data or payloads of information from your component to the global store object. \n\nConsider that the authentication is already in progress, in which case you do not want to dispatch the `AUTHENTICATE` action. So here, you need to connect the component to the global store and retrieve the authentication status. You can do that by passing the `mapStateToProps` argument to the `connect()` method. The condition will ensure that the `AUTHENTICATE` action is dispatched only when the `isAuthentication` state is set to `false`.\n\n```js\nimport React from \"react\";\nimport { connect } from \"react-redux\";\n\nclass LoginPage extends React.Component {\n  constructor(props) {\n    super(props);\n\n    this.handleFormSubmit = this.handleFormSubmit.bind(this);\n  }\n\n  handleFormSubmit(values) {\n    if (!this.props.isAuthenticating)\n      this.props.dispatch({\n        type: AUTHENTICATE,\n        payload: values,\n      });\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cLoginForm onSubmit={this.handleFormSubmit} /\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nconst mapStateToProps = (globalState) =\u003e {\n  const { isAuthenticating } = globalState;\n  return { isAuthenticating };\n};\n\nexport default connect(mapStateToProps)(LoginPage);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n","funding_links":[],"categories":["miscellaneous","Others"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Freact-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearning-zone%2Freact-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Freact-basics/lists"}