{"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,"funding_links":[],"categories":["miscellaneous","JavaScript","Others"],"sub_categories":[],"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 k","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"}