{"id":20076438,"url":"https://github.com/aakashdeveloper/react-interview-questions","last_synced_at":"2025-03-02T12:42:41.587Z","repository":{"id":98117241,"uuid":"359509002","full_name":"Aakashdeveloper/react-interview-questions","owner":"Aakashdeveloper","description":null,"archived":false,"fork":false,"pushed_at":"2025-01-12T03:41:53.000Z","size":3004,"stargazers_count":8,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-12T04:26:02.759Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/Aakashdeveloper.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":"2021-04-19T15:30:27.000Z","updated_at":"2025-01-12T03:41:57.000Z","dependencies_parsed_at":"2023-05-23T21:15:33.071Z","dependency_job_id":null,"html_url":"https://github.com/Aakashdeveloper/react-interview-questions","commit_stats":{"total_commits":1,"total_committers":1,"mean_commits":1.0,"dds":0.0,"last_synced_commit":"157f219adc6bddfde81ece559105a2fd30a11dd7"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2Freact-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2Freact-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2Freact-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2Freact-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Aakashdeveloper","download_url":"https://codeload.github.com/Aakashdeveloper/react-interview-questions/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241509618,"owners_count":19974070,"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":[],"created_at":"2024-11-13T15:02:59.776Z","updated_at":"2025-03-02T12:42:41.560Z","avatar_url":"https://github.com/Aakashdeveloper.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Interview Questions\n\n*Click \u003cimg src=\"assets/star.png\" width=\"18\" height=\"18\" align=\"absmiddle\" title=\"Star\" /\u003e if you like the project. Pull Request are highly appreciated.*\n\n\u003cbr/\u003e\n\n## Table of Contents\n\n* *[Create React Application](https://create-react-app.dev/docs/getting-started)*\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\n\u003cbr/\u003e\n\n## Q1. ***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**[[Read More](https://reactjs.org/tutorial/tutorial.html)]**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q2. ***How React works?***\n\nWhile building client-side apps, a team at Facebook developers realized that the DOM is slow (The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated). So, to make it faster, React 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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q3. ***What are Components in React?***\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/component-tree.png\" alt=\"Components Tree\" /\u003e\n\u003c/p\u003e\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\nA react application is made of multiple components, each responsible for rendering a small, reusable piece of HTML. Components can be nested within other components to allow complex applications to be built out of simple building blocks. A component may also maintain internal state – for example, a TabList component may store a variable corresponding to the currently open tab.\n\n*Example*: Class Component\n\n```js\nclass Welcome extends React.Component {\n  render() {\n    return \u003ch1\u003eHello, World!\u003c/h1\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q4. ***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 requered 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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q5. ***What is JSX and how JSX can help applications in React.js?***\n\nJSX 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\n*Example*:\n\n```js\nimport React from 'react'\n\nclass App extends React.Component {\n\n   render() {\n      return (\n         \u003cdiv\u003e\n            Hello World!\n         \u003c/div\u003e\n      )\n   }\n}\nexport default App\n```\n\n**JSX is a JavaScript Expression**\n\nJSX expressions are JavaScript expressions too. When 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\nSince they are compiled to objects, JSX can be used wherever a regular JavaScript expression can be used.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q6. ***What is ReactDOM?***\n\n`ReactDOM()` 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. ReactDOM provides the developers with an API containing following methods and a few more.\n\n* `render()`\n* `findDOMNode()`\n* `unmountComponentAtNode()`\n* `hydrate()`\n* `createPortal()`\n\nBefore **v0.14** React Dom was part of React. The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps.\n\nReactDOM uses observables thus provides an efficient way of DOM handling. ReactDOM can be used in both client-side and server-side.\n\n*Example*:\n\n```js\n// index.js\n\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport App from './App/App'\n\nReactDOM.render(\n  \u003cReact.StrictMode\u003e\n    \u003cApp /\u003e\n  \u003c/React.StrictMode\u003e,\n  document.getElementById('root')\n)\n```\n\nTo use the ReactDOM in any React web app we must first import ReactDOM from the react-dom package by using the following code snippet:\n\n```js\nimport ReactDOM from 'react-dom'\n```\n**a.) ReactDOM.render() Function**  \n\nThis function is used to render a single React Component or several Components wrapped together in a Component or a div element. This function uses the efficient methods of React for updating the DOM by being able to change only a subtree, efficient diff methods etc.\nThis function returns a reference to the component or null if a stateless component was rendered.\n\n`ReactDOM.render()` replaces the child of the given container if any. It uses highly efficient diff algorithm and can modify any subtree of the DOM.\n\n```jsx\nReactDOM.render(element, container, callback)\n```\n\n* **element**: This parameter expects a JSX expression or a React Element to be rendered.\n* **container**: This parameter expects the container in which the element has to be rendered.\n* **callback**: This is an optional parameter that expects a function that is to be executed once the render is complete.\n\n**b.) findDOMNode() Function**  \n\nThis function is generally used to get the DOM node where a particular React component was rendered. This method is very less used as the following can be done adding a ref attribute to each component itself.\n\n`findDOMNode()` function can only be implemented upon mounted components thus Functional components can not be used in findDOMNode() method.\n\n```jsx\nReactDOM.findDOMNode(component)\n```\n\nThis method takes a single parameter component which expects a React Component to be searched in the Browser DOM. This function returns the DOM node where the component was rendered on success otherwise null.\n\n**c.) unmountComponentAtNode() Function**  \n\nThis function is used to unmount or remove the React Component that was rendered to a particular container. \n\n```jsx\nReactDOM.unmountComponentAtNode(container)\n```\nThis method takes a single parameter container which expects the DOM container from which the React component has to be removed. This function returns true on success otherwise false.\n\n**d.) hydrate() Function**  \n\nThis method is equivalent to the render() method but is implemented while using server-side rendering.\n\n```jsx\nReactDOM.hydrate(element, container, callback)\n```\n\n* **element**: This parameter expects a JSX expression or a React Component to be rendered.\n* **container**: This parameter expects the container in which the element has to be rendered.\n* **callback**: This is an optional parameter that expects a function that is to be executed once the render is complete.\n\nThis 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**e.) createPortal() Function**  \n\nUsually, when an element is returned from a component\\'s render method, it\\'s mounted on the DOM as a child of the nearest parent node which in some cases may not be desired. Portals allow us to render a component into a DOM node that resides outside the current DOM hierarchy of the parent component.\n\n```jsx\nReactDOM.createPortal(child, container)\n```\n\n* **child**: This parameter expects a JSX expression or a React Component to be rendered.\n* **container**: This parameter expects the container in which the element has to be rendered.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q7. ***What is the difference between ReactDOM and React?***\n\n```js\nimport React from 'react' /* importing react */\nimport ReactDOM from 'react-dom' /* importing react-dom */\n\nclass MyComponent extends React.Component {\n\n  render() {\n    return \u003cdiv\u003eHello World\u003c/div\u003e\n  }\n})\n\nReactDOM.render(\u003cMyComponent /\u003e, node)\n\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\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\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q8. ***What are the differences between a class component and functional component?***\n\n**Functional Components**  \n\n* Functional components are basic JavaScript functions. These are typically arrow functions but can also be created with the regular  function keyword.\n* Sometimes referred to as `stateless` components as they simply accept data and display them in some form; that is they are mainly responsible for rendering UI.\n* React lifecycle methods (for example, `componentDidMount()`) cannot be used in functional components.\n* There is no render method used in functional components.\n* These are mainly responsible for UI and are typically presentational only (For example, a Button component).\n* Functional components can accept and use props.\n* Functional components should be favored if you do not need to make use of React state.\n\n*Example*:\n```js\nconst ClockUsingHooks = props =\u003e {\n    const [time, setTime] = useState(new Date())\n\n    const changeTime = () =\u003e {\n        setTime(new Date())\n    }\n\n    useEffect(() =\u003e {\n        const tick = setInterval(() =\u003e {\n            changeTime()\n        }, 1000)\n        return () =\u003e clearInterval(tick)\n    })\n    return (\n        \u003cdiv className=\"clock\"\u003e\n            \u003ch1\u003eHello! This is a function component clock.\u003c/h1\u003e\n            \u003ch2\u003eIt is {time.toLocaleTimeString()}.\u003c/h2\u003e\n        \u003c/div\u003e\n    )\n}\n\nexport default ClockUsingHooks\n```\n\n**Class Components**  \n\n* Class components make use of ES6 class and extend the Component class in React.\n* Sometimes called `stateful` components as they tend to implement logic and state.\n* React lifecycle methods can be used inside class components (for example, `componentDidMount()`).\n* We pass `props` down to class components and access them with `this.props`.\n* Class-based components can have `refs` to underlying DOM nodes.\n* Class-based components can use `shouldComponentUpdate()` and `PureComponent()` performance optimisation techniques.\n\n*Example*:\n```js\nclass ClockUsingClass extends React.Component {\n    constructor(props) {\n        super(props)\n        this.state = { date: new Date() }\n    }\n\n    componentDidMount() {\n        this.time = setInterval(() =\u003e {\n            this.changeTime()\n        }, 1000)\n    }\n\n    componentWillUnmount() {\n        clearInterval(this.time)\n    }\n\n    changeTime() {\n        this.setState({ date: new Date() })\n    }\n\n    render() {\n        return (\n            \u003cdiv className=\"clock\"\u003e\n                \u003ch1\u003eHello! This is a class component clock.\u003c/h1\u003e\n                \u003ch2\u003eIt is {this.state.date.toLocaleTimeString()}.\u003c/h2\u003e\n            \u003c/div\u003e\n        )\n    }\n}\n\nexport default ClockUsingClass\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q9. ***What is the difference between state and props?***\n\n**State**  \n\nThis is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the `setState()` function.\n\n*Example*:\n\n```js\nclass Employee extends React.Component {\n    constructor() {\n        this.state = {\n            id: 1,\n            name: \"Alex\"\n        }  \n    }\n\n    render() {\n        return (\n            \u003cdiv\u003e\n              \u003cp\u003e{this.state.id}\u003c/p\u003e\n              \u003cp\u003e{this.state.name}\u003c/p\u003e\n            \u003c/div\u003e\n        )  \n    }\n}\n\nexport default Employee\n```\n\n**Props**  \n\nData passed in from a parent component. `props` are read-only in the child component that receives them. However, callback functions can also be passed, which can be executed inside the child to initiate an update.\n\n*Example*:\n\n```js\nclass ParentComponent extends Component {\n    render() {\n        return (\n            \u003cChildComponent name=\"First Child\" /\u003e\n        )  \n    }\n}\n\nconst ChildComponent = (props) =\u003e {\n    return \u003cp\u003e{props.name}\u003c/p\u003e\n}\n```\n\n**Difference between State and Props**  \n\n|Props                             |State                             |\n|----------------------------------|----------------------------------|\n|Props are read-only.              |State changes can be asynchronous.|\n|Props are immutable.              |State is mutable.                 |\n|Props allow you to pass data from one component to other components as an argument.|\tState holds information about the components.|\n|Props can be accessed by the child component.    |State cannot be accessed by child components.|\n|Props are used to communicate between components.|States can be used for rendering dynamic changes with the component.|\n|Stateless component can have Props.            |Stateless components cannot have State.|\n|Props make components reusable.                 |State cannot make components reusable.|\n|Props are external and controlled by whatever renders the component.|The State is internal and controlled by the React Component itself.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q10. ***How would you create Higher Order Components (HOCs) in React.js?***\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/Higher-Order-Components.jpg\" alt=\"Higher Order Components\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nA higher-order component is a function that takes a component and returns a new component. A higher-order component (HOC) is the advanced technique in React.js for reusing a component logic. Higher-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// HOC.js\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\n```js\n// App.js\n\nimport React, { Component } from 'react'\nimport Hoc from './HOC'\n\nclass App extends Component {\n  \n  render() {\n    return (\n      \u003cdiv\u003e\n        Higher-Order Component Example!\n      \u003c/div\u003e\n    )\n  }\n}\nApp = Hoc(App)\nexport default App\n```\n\n*Notes*\n\n* We do not modify or mutate components. We create new ones.\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\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q11. ***What is PureComponent?***\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. If the value of the previous state or props and the new state or props is the same, the component is not re-rendered. 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\nSimilar to Pure Functions in JavaScript, a React component is considered a Pure Component if it renders the same output for the same state and props value. React provides the `PureComponent` base class for these class components. Class components that extend the `React.PureComponent` class are treated as pure components.\n\nIt is the same as Component except that Pure Components take care of `shouldComponentUpdate()` by itself, it does the *shallow comparison* on the state and props data. If the previous state and props data is the same as the next props or state, the component is not Re-rendered.\n\nReact Components re-renders in the following scenarios:\n\n1. `setState()` is called in Component\n1. `props` values are updated\n1. `this.forceUpdate()` is called\n\nIn the case of Pure Components, the React components do not re-render blindly without considering the updated values of React `props` and `state`. If updated values are the same as previous values, render is not triggered.\n\n**Stateless Component**\n\n```js\nimport { pure } from 'recompose'\n\nexport default pure ( (props) =\u003e {\n   return 'Stateless Component Example'\n})\n```\n\n**Stateful Component**\n\n```js\nimport React, { PureComponent } from 'react'\n\nexport default class Test extends PureComponent{\n   render() {\n      return 'Stateful Component Example'\n   }\n}\n```\n\n*Example*:\n\n```js\nclass Test extends React.PureComponent {\n   constructor(props) {\n      super(props)\n      this.state = {\n         taskList: [\n            { title: 'Excercise'},\n            { title: 'Cooking'},\n            { title: 'Reacting'},\n         ]\n      }\n   }\n   componentDidMount() {\n      setInterval(() =\u003e {\n         this.setState((oldState) =\u003e {\n            return { taskList: [...oldState.taskList] }\n         })\n      }, 1000)\n   }\n   render() {\n      console.log(\"TaskList render() called\")\n      return (\u003cdiv\u003e\n         {this.state.taskList.map((task, i) =\u003e {\n            return (\u003cTask\n               key={i}\n               title={task.title}\n            /\u003e)\n         })}\n      \u003c/div\u003e)\n   }\n}\nclass Task extends React.Component {\n   render() {\n      console.log(\"task added\")\n      return (\u003cdiv\u003e\n         {this.props.title}\n      \u003c/div\u003e)\n   }\n}\nReactDOM.render(\u003cTest /\u003e, document.getElementById('app'))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q12. ***Why to use PureComponent? When to use PureComponent over Component?***\n\nBoth functional-based and class-based components have the same downside: they always re-render when their parent component re-renders even if the props do not change.\n\nAlso, class-based components always re-render when its state is updated (`this.setState()` is called) even if the new state is equal to the old state. Moreover, when a parent component re-renders, all of its children are also re-rendered, and their children too, and so on.\n\nThat behaviour may mean a lot of wasted re-renderings. Indeed, if our component only depends on its props and state, then it shouldn’t re-render if neither of them changed, no matter what happened to its parent component.\n\nThat is precisely what PureComponent does - it stops the vicious re-rendering cycle. PureComponent does not re-render unless its props and state change.\n\n**When to use PureComponent**  \n\n* We want to avoid re-rendering cycles of component when its props and state are not changed, and\n* The state and props of component are immutable, and\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, or\n* Plan to implement own `shouldComponentUpdate()` lifecycle method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q13. ***How Virtual-DOM is more efficient than Dirty checking?***\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/virtualdom-vs-realdom.png\" alt=\"Virtual DOM\" with=\"500px\" /\u003e\n\u003c/p\u003e\n\n**React Virtual DOM**  \n\nIn React, Each time the DOM updates or data of page changes, a new Virtual DOM representation of the user interface is made. It is just a lightweight copy or DOM.\n\nVirtual DOM in React has almost same properties like a real DOM, but it can not directly change the content on the page. Working with Virtual DOM is faster as it does not update anything on the screen at the same time. In a simple way, Working with Virtual DOM is like working with a copy of real DOM nothing more than that. \n\nUpdating virtual DOM in ReactJS is faster because ReactJS uses\n\n1. It is efficient diff algorithm.\n1. It batched update operations\n1. It efficient update of sub tree only\n1. It uses observable instead of dirty checking to detect change\n\n**How Virtual DOM works in React**  \n\nWhen we render a JSX element, each virtual DOM updates. This approach updates everything very quickly. Once the Virtual DOM updates, React matches the virtual DOM with a virtual DOM copy that was taken just before the update. By Matching the new virtual DOM with pre-updated version, React calculates exactly which virtual DOM has changed. This entire process is called **diffing**.\n\nWhen React knows which virtual DOM has changed, then React updated those objects. and only those object, in the real DOM. React only updates the necessary parts of the DOM. React\\'s reputation for performance comes largely from this innovation.\n\nIn brief, here is what happens when we update the DOM in React:\n\n1. The entire virtual DOM gets updated.\n1. The virtual DOM gets compared to what it looked like before you updated it. React matches out which objects have changed.\n1. The changed objects and the changed objects only get updated on the real DOM.\n1. Changes on the real DOM cause the screen to change finally.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q14. ***Why is setState() in React async instead of sync?***\n\nEven if state is updated synchronously, props are not, it mens we do not know props until it re-render the parent component. The objects provided by React (`state`, `props`, `refs`) are consistent with each other and if you introduce a synchronous setState you could introduce some bugs.\n\n`setState()` does not immediately mutate `this.state()` but creates a pending state transition. Accessing `this.state()` after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to `setState()` and calls may be batched for performance gains.\n\nThis is because setState() alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus the setState() calls are asynchronous as well as batched for better UI experience and performance.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q15. ***What are controlled and uncontrolled components in React?***\n\nIn a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.\n\n**Controlled Components**  \n\nIn a controlled component, the form data is handled by the state within the component. The state within the component serves as “the single source of truth” for the input elements that are rendered by the component.\n\n*Example*:\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n    state = {\n        message: ''\n    }\n    updateMessage = (newText) =\u003e {\n        console.log(newText)\n        this.setState(() =\u003e ({\n            message: newText\n        }))\n    }\n    render() {\n        return (\n            \u003cdiv className=\"App\"\u003e\n                \u003cdiv className=\"container\"\u003e\n                    \u003cinput type=\"text\"\n                        placeholder=\"Your message here..\"\n                        value={this.state.message}\n                        onChange={(event) =\u003e this.updateMessage(event.target.value)}\n                    /\u003e\n                    \u003cp\u003ethe message is: {this.state.message}\u003c/p\u003e\n                \u003c/div\u003e\n            \u003c/div\u003e\n        )\n    }\n}\n\nexport default App\n```\n\n**Uncontrolled Components**  \n\nUncontrolled components act more like traditional HTML form elements. The data for each input element is stored in the DOM, not in the component. Instead of writing an event handler for all of your state updates, It uses `ref` to retrieve values from the DOM. `Refs` provide a way to access DOM nodes or React elements created in the render method.\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n\n    constructor(props){\n        super(props)\n        this.handleChange = this.handleChange.bind(this)\n        this.input = React.createRef()\n    }\n    handleChange = (newText) =\u003e {\n        console.log(newText)\n    }\n    render() {\n        return (\n            \u003cdiv className=\"App\"\u003e\n                \u003cdiv className=\"container\"\u003e\n                    \u003cinput type=\"text\"\n                        placeholder=\"Your message here..\"\n                        ref={this.input}\n                        onChange={(event) =\u003e this.handleChange(event.target.value)}\n                    /\u003e\n                \u003c/div\u003e\n            \u003c/div\u003e\n        )\n    }\n}\nexport default App\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q16. ***What is React.cloneElement?***\n\nThe `React.cloneElement()` function returns a copy of a specified element. Additional props and children can be passed on in the function. This function is used when a parent component wants to add or modify the prop(s) of its children.\n\n```js\nReact.cloneElement(element, [props], [...children])\n```\nThe react.cloneElement() method accepts three arguments.\n\n* element: Element we want to clone.\n* props: props we need to pass to the cloned element.\n* children: we can also pass children to the cloned element (passing new children replaces the old children).\n\nExample\n```js\nimport React from 'react'\n\nexport default class App extends React.Component {\n\n  // rendering the parent and child component\n  render() {\n    return (\n      \u003cParentComp\u003e\n        \u003cMyButton/\u003e\n        \u003cbr\u003e\u003c/br\u003e\n        \u003cMyButton/\u003e\n      \u003c/ParentComp\u003e\n    )\n  }\n}\n// The parent component\nclass ParentComp extends React.Component {\n  render() {\n    // The new prop to the added.\n    let newProp = 'red'\n      // Looping over the parent's entire children,\n      // cloning each child, adding a new prop.\n    return (\n      \u003cdiv\u003e\n        {React.Children.map(this.props.children,\n          child =\u003e {\n            return React.cloneElement(child,\n            {newProp}, null)\n        })}\n      \u003c/div\u003e\n    )\n  }\n}\n// The child component\nclass MyButton extends React.Component {\n  render() {\n    return \u003cbutton style =\n    {{ color: this.props.newProp }}\u003e\n    Hello World!\u003c/button\u003e\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q17. ***When we should use React.cloneElement vs this.props.children?***\n\nThe `React.cloneElement()` works if child is a single React element.\n\nFor almost everything `{this.props.children}` is used. Cloning is useful in some more advanced scenarios, where a parent sends in an element and the child component needs to change some props on that element or add things like `ref` for accessing the actual DOM element.\n\n**React.Children**  \n\nSince `{this.props.children}` can have one element, multiple elements, or none at all, its value is respectively a single child node, an array of child nodes or undefined. Sometimes, we want to transform our children before rendering them — for example, to add additional props to every child. If we wanted to do that, we\\'d have to take the possible types of `this.props.children` into account. For example, if there is only one child, we can not map it.\n\n*Example*:\n\n```js\nclass Example extends React.Component {\n\n  render() {\n    return \u003cdiv\u003e\n      \u003cdiv\u003eChildren ({this.props.children.length}):\u003c/div\u003e\n      {this.props.children}\n    \u003c/div\u003e\n  }\n}\n\nclass Widget extends React.Component {\n\n  render() {\n    return \u003cdiv\u003e\n      \u003cdiv\u003eFirst \u003ccode\u003eExample\u003c/code\u003e:\u003c/div\u003e\n      \u003cExample\u003e\n        \u003cdiv\u003e1\u003c/div\u003e\n        \u003cdiv\u003e2\u003c/div\u003e\n        \u003cdiv\u003e3\u003c/div\u003e\n      \u003c/Example\u003e\n      \u003cdiv\u003eSecond \u003ccode\u003eExample\u003c/code\u003e with different children:\u003c/div\u003e\n      \u003cExample\u003e\n        \u003cdiv\u003eA\u003c/div\u003e\n        \u003cdiv\u003eB\u003c/div\u003e\n      \u003c/Example\u003e\n    \u003c/div\u003e\n  }\n}\n```\nOutput\n```\nFirst Example:\nChildren (3):\n1\n2\n3\nSecond Example with different children:\nChildren (2):\nA\nB\n```\n`children` is a special property of React components which contains any child elements defined within the component, e.g. the `\u003cdiv\u003e` inside Example above. `{this.props.children}` includes those children in the rendered result.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q18. ***What is the second argument that can optionally be passed to setState and what is its purpose?***\n\nA callback function which will be invoked when `setState()` has finished and the component is re-rendered.\n\nThe `setState()` is asynchronous, which is why it takes in a second callback function. Typically it\\'s best to use another lifecycle method rather than relying on this callback function, but it is good to know it exists.\n\n```js\nthis.setState(\n  { username: 'Alex' },\n  () =\u003e console.log('setState has finished and the component has re-rendered.')\n)\n```\nThe `setState()` will always lead to a re-render unless `shouldComponentUpdate()` returns false. To avoid unnecessary renders, calling `setState()` only when the new state differs from the previous state makes sense and can avoid calling `setState()` in an infinite loop within certain lifecycle methods like `componentDidUpdate()`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q19. ***What is useState() in React?***\n\nThe `useState()` is a Hook that allows to have state variables in functional components.\n\n```js\nimport React, { useState } from 'react'\n\nconst App = () =\u003e {\n  const [count, setCount] = React.useState(0)\n\n  const handleIncrease = () =\u003e {\n    setCount(count + 1)\n  }\n\n  const handleDecrease = () =\u003e {\n    setCount(count - 1)\n  }\n\n  return (\n    \u003cdiv\u003e\n      Count: {count}\n      \u003chr /\u003e\n      \u003cdiv\u003e\n        \u003cbutton type=\"button\" onClick={handleIncrease}\u003e\n          Increase\n        \u003c/button\u003e\n        \u003cbutton type=\"button\" onClick={handleDecrease}\u003e\n          Decrease\n        \u003c/button\u003e\n      \u003c/div\u003e\n    \u003c/div\u003e\n  )\n}\n```\nThe useState() function takes as argument a value for the initial state. In this case, the count starts out with 0. In addition, the hook returns an array of two values: **count** and **setCount**. It\\'s up to you to name the two values, because they are `destructured from the returned array` where renaming is allowed.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q20. ***What is useReducer() in React?***\n\nIt accepts a reducer function with the application initial state, returns the current application state, then dispatches a function.\n\nAlthough `useState()` is a Basic Hook and `useReducer()` is an Additional Hook, `useState()` is actually implemented with `useReducer()`. This means `useReducer()` is primitive and we can use `useReducer()` for everything can do with useState(). Reducer is so powerful that it can apply for various use cases.\n\n*Example*:\n\n```js\nimport React, { useReducer } from 'react'\n\nconst initialState = 0\nconst reducer = (state, action) =\u003e {\n  switch (action) {\n    case 'increment': return state + 1\n    case 'decrement': return state - 1\n    case 'reset': return 0\n    default: throw new Error('Unexpected action')\n  }\n}\n\nconst ReducerExample = () =\u003e {\n  const [count, dispatch] = useReducer(reducer, initialState)\n  return (\n    \u003cdiv\u003e\n      {count}\n      \u003cbutton onClick={() =\u003e dispatch('increment')}\u003e+1\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch('decrement')}\u003e-1\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e dispatch('reset')}\u003ereset\u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default ReducerExample\n```\nHere, we first define an initialState and a reducer. When a user clicks a button, it will dispatch an action which updates the count and the updated count will be displayed. We could define as many actions as possible in the reducer, but the limitation of this pattern is that actions are finite.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q21. ***What is useContext() in React?***\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/context-api.jpg\" alt=\"Context API\" width=\"800px\" /\u003e\n\u003c/p\u003e\n\nThe React Context API allows to easily access data at different levels of the component tree, without having to pass data down through `props`.\n\n```js\nimport React from \"react\"\nimport ReactDOM from \"react-dom\"\n\n// Create a Context\nconst NumberContext = React.createContext()\n// It returns an object with 2 values:\n// { Provider, Consumer }\n\nfunction App() {\n  // Use the Provider to make a value available to all\n  // children and grandchildren\n  return (\n    \u003cNumberContext.Provider value={10}\u003e\n      \u003cdiv\u003e\n        \u003cDisplay /\u003e\n      \u003c/div\u003e\n    \u003c/NumberContext.Provider\u003e\n  )\n}\n\nfunction Display() {\n  const value = useContext(NumberContext)\n  return \u003cdiv\u003eThe answer is {value}.\u003c/div\u003e\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q22. ***What is difference between useEffect() vs componentDidMount()?***\n\nIn react when we use class based components we get access to lifecycle methods(like componentDidMount, componentDidUpdat, 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\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//Using a class based component.\nimport React, { Component } from 'react'\n\nexport default class SampleComponent extends Component {\n  componentDidMount() {\n    // code to run on component mount\n  }\nrender() {\n    return (\u003cdiv\u003efoo\u003c/div\u003e)\n  }\n}\n\n//Using a functional component\nimport React, { useEffect } from 'react'\n\nconst SampleComponent = () =\u003e {\n  useEffect(() =\u003e {\n    // code to run on component mount\n  }, [])\nreturn (\u003cdiv\u003efoo\u003c/div\u003e)\n}\nexport SampleComponent\n```\n\n**useEffect() Limitations**\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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q23. ***What do you understand by refs in React?***\n\n`Refs` provide a way to access DOM nodes or React elements created in the render method. React Refs are a useful feature that act as a means to reference a DOM element or a class component from within a parent component.\n\nRefs also provide some flexibility for referencing elements within a child component from a parent component, in the form of ref forwarding.\n\n*Example*:\n\n```javascript\nclass App extends React.Component {\n    constructor(props) {\n      super(props)\n      // create a ref to store the textInput DOM element\n      this.textInput = React.createRef()\n      this.state = {\n        value: ''\n      }\n    }\n  \n  // Set the state for the ref\n  handleSubmit = e =\u003e {\n    e.preventDefault()\n    this.setState({ value: this.textInput.current.value})\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eReact Ref - createRef\u003c/h1\u003e\n         {/** This is what will update **/}\n        \u003ch3\u003eValue: {this.state.value}\u003c/h3\u003e\n        \u003cform onSubmit={this.handleSubmit}\u003e\n          {/** Call the ref on \u003cinput\u003e so we can use it to update the \u003ch3\u003e value **/}\n          \u003cinput type=\"text\" ref={this.textInput} /\u003e\n          \u003cbutton\u003eSubmit\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n**When to Use Refs**  \n\n* Managing focus, text selection, or media playback.\n* Triggering imperative animations.\n* Integrating with third-party DOM libraries.\n\n**When not to use refs**  \n\n* Should not be used with functional components because they dont have instances.\n* Not to be used on things that can be done declaritvely.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q24. ***What will happen if you use setState() in constructor?***\n\nWhen we use `setState()`, then apart from assigning to the object state react also rerenders the component and all it\\'s children. Which we don\\'t need in the constructor, since the component hasn\\'t been rendered anyway.\n\nInside constructor uses `this.state = {}` directly, other places use `this.setState({ })`\n\n*Example*:\n\n```js\nimport React, { Component } from 'react'\n\nclass Food extends Component {\n\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      fruits: ['apple', 'orange'],\n      count: 0\n    }\n  }\n  render() {\n    return (\n      \u003cdiv className = \"container\"\u003e\n        \u003ch2\u003e Hello!!!\u003c/h2\u003e\n        \u003cp\u003e I have {this.state.count} fruit(s)\u003c/p\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q25. ***What is the difference between DOM and virtual DOM?***\n\n**DOM**\n\nDOM stands for \"Document Object Model\". The HTML DOM provides an interface (API) to traverse and modify the nodes. It contains methods like `getElementById()` or `removeChild()`.\n\nThe DOM is represented as a tree data structure. Because of that, the changes and updates to the DOM are fast. But after the change, the updated element and it\\'s children have to be re-rendered to update the application UI. The re-rendering or re-painting of the UI is what makes it slow.\n\n**Virtual DOM**  \n\nThe virtual DOM is only a virtual representation of the DOM. Everytime the state of our application changes, the virtual DOM gets updated instead of the real DOM.\n\nThe Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction.\n\n**Why Virtual DOM is faster**\n\nWhen new elements are added to the UI, a virtual DOM, which is represented as a tree is created. Each element is a node on this tree. If the state of any of these elements changes, a new virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual DOM tree.\n\nOnce this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM.\n\n**Pros of Virtual DOM**  \n\n* Updates process is optimized and accelerated.\n* JSX makes components/blocks code readable.\n* React data binding establishes conditions for creation dynamic applications.\n* Virtual DOM is ideal for mobile first applications.\n* Prompt rendering. Using comprises methods to minimize number of DOM operations helps to optimize updating process and accelerate it.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/dom.png\" alt=\"Real DOM and Virtual DOM\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q26. ***When should we use arrow functions with React?***\n\n**Arrows prevent `this` bugs**\n\nArrow functions don not redefine the value of `this` within their function body. This makes it a lot easier to predict their behavior when passed as callbacks, and prevents bugs caused by use of this within callbacks. Using inline arrow functions in function components is a good way to achieve some decoupling.\n\n*Example*:\n\n```js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\n\nclass Button extends React.Component {\n  render() {\n    return (\n      \u003cbutton onClick={this.handleClick} style={this.state}\u003e\n        Set background to red\n      \u003c/button\u003e\n    )\n  }\n\n  handleClick = () =\u003e {\n    this.setState({ backgroundColor: 'red' })\n  }\n}\n\nReactDOM.render(\n  \u003cButton /\u003e,\n  document.getElementById('root')\n)\n```\n1. When we use `this` it generates a new function on every render, which will obviously have a new reference.\n2. If the component we pass this generated function to is extending `PureComponent()`, it will not be able to bail out on rerendering, even if the actual data has not changed.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q27. ***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 Main extends Component {\n constructor() {\n   super()\n   this.state = {\n     books: []\n   }\n }\n render() {\n   \u003cBooksList books={this.state.books} /\u003e\n }\n}\n```\n\n*Example*: Stateless/Presentational/Dumb component\n\n```js\nconst BooksList = ({books}) =\u003e {\n return (\n   \u003cul\u003e\n     {books.map(book =\u003e {\n       return \u003cli\u003ebook\u003c/li\u003e\n     })}\n   \u003c/ul\u003e\n )\n}\n```\n**Functional Component or Stateless component**  \n\n* Functional component is like pure function in JavaScript.\n* Functional component is also called as a stateless component.\n* The functional component only receives props from parent component and return you JSX elements.\n* The functional component doesn’t play with any lifecycle methods of React and doesn’t play with the component state.\n\n**Class component or statefull component**  \n\n* React class component is called as a stateful component.\n* Stateful component plays with all life cycle methods of React.\n* This component will modify state.\n\n**When would you use a stateless component**\n\n* When you just need to present the props\n* When you do not need a state, or any internal variables\n* When creating element does not need to be interactive\n* When you want reusable code\n\n**When would you use a stateful component?**  \n\n* When building element that accepts user input or element that is interactive on page\n* When dependent on state for rendering, such as, fetching data before rendering\n* When dependent on any data that cannot be passed down as props\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q28. ***What are the different phases of React component lifecycle?***\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\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**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**constructor**  \n\nThe `constructor()` method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values.\n\nThe `constructor()` method is called with the `props`, as arguments, and we should always start by calling the `super(props)` before anything else, this will initiate the parent\\'s constructor method and allows the component to inherit methods from its parent (`React.Component`).\n\n**getDerivedStateFromProps**\n\nThe `getDerivedStateFromProps()` method is called right before rendering the element(s) in the DOM. It takes state as an argument, and returns an object with changes to the state.\n\n*Example*:\n\n```js\nclass Color extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {color: \"red\"}\n  }\n  static getDerivedStateFromProps(props, state) {\n    return {color: props.favcol }\n  }\n  render() {\n    return (\n      \u003ch1\u003eMy Favorite Color is {this.state.color}\u003c/h1\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cColor favcol=\"yellow\"/\u003e, document.getElementById('root'))\n```\n\n**render()**\n\nThe render() method is required, and is the method that actual outputs HTML to the DOM.\n\n**componentDidMount()**  \n\nThe `componentDidMount()` method is called after the component is rendered.\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**getDerivedStateFromProps**  \n\nThis is the first method that is called when a component gets updated. This is still the natural place to set the state object based on the initial props.\n\n*Example*:\n\n```js\nclass Color extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {color: \"red\"}\n  }\n  static getDerivedStateFromProps(props, state) {\n    return {color: props.favcol }\n  }\n  changeColor = () =\u003e {\n    this.setState({color: \"blue\"})\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n      \u003ch1\u003eMy Favorite Color is {this.state.color}\u003c/h1\u003e\n      \u003cbutton type=\"button\" onClick={this.changeColor}\u003eChange color\u003c/button\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cColor favcol=\"yellow\"/\u003e, document.getElementById('root'))\n```\n\n**shouldComponentUpdate**\n\nIn the `shouldComponentUpdate()` method you can return a Boolean value that specifies whether React should continue with the rendering or not. The default value is `true`.\n\n```js\nclass Color extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {color: \"red\"}\n  }\n  shouldComponentUpdate() {\n    return false\n  }\n  changeColor = () =\u003e {\n    this.setState({color: \"blue\"})\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n      \u003ch1\u003eMy Favorite Color is {this.state.color}\u003c/h1\u003e\n      \u003cbutton type=\"button\" onClick={this.changeColor}\u003eChange color\u003c/button\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cColor /\u003e, document.getElementById('root'))\n```\n\n**render()**\n\nThe `render()` method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.\n\n**getSnapshotBeforeUpdate**\n\nIn the `getSnapshotBeforeUpdate()` method we have access to the `props` and `state` before the update, meaning that even after the update, we can check what the values were before the update.\n\nIf the `getSnapshotBeforeUpdate()` method is present, we should also include the `componentDidUpdate()` method, otherwise it will throw an error.\n\n*Example*:\n\n```js\nclass Color extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {color: \"red\"}\n  }\n  componentDidMount() {\n    setTimeout(() =\u003e {\n      this.setState({color: \"yellow\"})\n    }, 1000)\n  }\n  getSnapshotBeforeUpdate(prevProps, prevState) {\n    document.getElementById(\"div1\").innerHTML =\n    \"Before the update, the favorite was \" + prevState.color\n  }\n  componentDidUpdate() {\n    document.getElementById(\"div2\").innerHTML =\n    \"The updated favorite is \" + this.state.color\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003ch1\u003eMy Favorite Color is {this.state.color}\u003c/h1\u003e\n        \u003cdiv id=\"div1\"\u003e\u003c/div\u003e\n        \u003cdiv id=\"div2\"\u003e\u003c/div\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cColor /\u003e, document.getElementById('root'))\n```\n\n**componentDidUpdate**  \n\nThe `componentDidUpdate()` method is called after the component is updated in the DOM.\n\n*Example*:\n\n```js\nclass Color extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {color: \"red\"}\n  }\n  componentDidMount() {\n    setTimeout(() =\u003e {\n      this.setState({color: \"yellow\"})\n    }, 1000)\n  }\n  componentDidUpdate() {\n    document.getElementById(\"mydiv\").innerHTML =\n    \"The updated favorite is \" + this.state.color\n  }\n  render() {\n    return (\n      \u003cdiv\u003e\n      \u003ch1\u003eMy Favorite Color is {this.state.color}\u003c/h1\u003e\n      \u003cdiv id=\"mydiv\"\u003e\u003c/div\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cColor /\u003e, document.getElementById('root'))\n```\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*Example*: Click the button to delete the header\n\n```js\nclass Container extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {show: true}\n  }\n  delHeader = () =\u003e {\n    this.setState({show: false})\n  }\n  render() {\n    let myheader\n    if (this.state.show) {\n      myheader = \u003cChild /\u003e\n    }\n    return (\n      \u003cdiv\u003e\n      {myheader}\n      \u003cbutton type=\"button\" onClick={this.delHeader}\u003eDelete Header\u003c/button\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nclass Child extends React.Component {\n  componentWillUnmount() {\n    alert(\"The component named Header is about to be unmounted.\")\n  }\n  render() {\n    return (\n      \u003ch1\u003eHello World!\u003c/h1\u003e\n    )\n  }\n}\n\nReactDOM.render(\u003cContainer /\u003e, document.getElementById('root'))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q29. ***What is the significance of keys in React?***\n\nKeys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.\n\n```js\nfunction NumberList(props) {\n\n  const numbers = props.numbers\n  const listItems = numbers.map((number) =\u003e\n    \u003cli key={number.toString()}\u003e\n      {number}\n    \u003c/li\u003e\n  )\n  return (\n    \u003cul\u003e{listItems}\u003c/ul\u003e\n  )\n}\n\nconst numbers = [1, 2, 3, 4, 5]\nReactDOM.render(\n  \u003cNumberList numbers={numbers} /\u003e,\n  document.getElementById('root')\n)\n```\n\n**Exceptions where it is safe to use index as key**\n\n* If your list is static and will not change.\n* The list will never be re-ordered.\n* The list will not be filtered (adding/removing items from the list).\n* There are no ids for the items in the list.\n\n*Note: Using `index` as a key can lead to potential unexpected behaviour within the component.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q30. ***What is React Router? Why is switch keyword used in React Router v4?***\n\nReact router implements a component-based approach to routing. It provides different routing components according to the needs of the application and platform. React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy loading, dynamic route matching, and location transition handling built right in.\n\n```bash\nnpm install react-router-dom\n```\n\n```js\nimport React, { Component } from 'react'\nimport { Router, Route, Redirect, Switch } from 'react-router-dom'\n\nimport Todos from './components/Todos/Todos'\nimport TodosNew from './components/TodosNew/TodosNew'\nimport TodoShow from './components/TodoShow/TodoShow'\n\nclass Router extends Component {\n    constructor(props) {\n        super(props)\n    }\n\n    render() {\n        return (\n            \u003cRouter\u003e\n                \u003cSwitch\u003e\n                    \u003cRoute path='/todos/new' component={ TodosNew } /\u003e\n                    \u003cRoute path='/todos/:id' component={ TodoShow } /\u003e\n                    \u003cRoute exact path='/' component={ Todos } /\u003e\n                    \u003cRedirect from='*' to='/' /\u003e\n                \u003c/Switch\u003e\n            \u003c/Router\u003e\n        )\n    }\n}\n\nexport default Router\n```\n\n**`\u003c Router /\u003e`**  \n\nThe `\u003c Router /\u003e` component wraps our main application routing. Nested within Router will be all of our `\u003c Route /\u003e` components, which will point to all other URLs.\n\n**`\u003cSwitch /\u003e`**\n\nThe Switch component helps us to render the components only when path matches otherwise it fallbacks to the not found component. The `\u003cSwitch\u003e` returns only one first matching route.\n\n**exact**\n\nThe `exact` returns any number of routes that match exactly.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q31. ***Explain the standard JavaScript toolchain, transpilation (via Babel or other compilers), JSX, and these items significance in recent development?***\n\nTypically, we use build tools like Grunt, Watchify/Browserify, Broccoli, or Webpack to watch the filesystem for file events (like when you add or edit a file). After this occurs, the build tool is configured to carry out a group of sequential or parallel tasks.\n\nThe rest of the tools belong in that group of sequential or parallel tasks:\n\n* *Style linting* - typically a linter like JSCS is used to ensure the source code is following a certain structure and style\n* *Dependency Management* - for JavaScript projects, most people use other packages from npm; some plugins exist for build systems (e.g. Webpack) and compilers (e.g. Babel) that allow automatic installation of packages being imported or require()‘d\n* *Transpilation* - a specific sub-genre of compilation, transpilation involves compiling code from one source version to another, only to a similar runtime level (e.g. ES6 to ES5)\n* *Compilation* - specifically separate from transpiling ES6 and JSX to ES5, is the act of including assets, processing CSS files as JSON, or other mechanisms that can load and inject external assets and code into a file. In addition, there are all sorts of build steps that can analyze your code and even optimize it for you.\n* *Minification and Compression* - typically part of – but not exclusively controlled by – compilation, is the act of minifying and compressing a JS file into fewer and/or smaller files\n* *Source-Mapping* - another optional part of compilation is building source maps, which help identify the line in the original source code that corresponds with the line in the output code (i.e. where an error occurred)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q32. ***How React handle or restrict Props to certain types?***\n\nReact `PropTypes` are a good way to help you catching bugs by validating data types of values passed through `props`. They also offer possibilities to flag props as mandatory or set default values.\n\n*Example*:\n\n```js\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nconst Person = (props) =\u003e \u003cdiv\u003e\n  \u003ch1\u003e{props.firstName} {props.lastName}\u003c/h1\u003e\n  {props.country ? \u003cp\u003eCountry: {props.country}\u003c/p\u003e : null}\n\u003c/div\u003e\n\nPerson.propTypes = {\n  firstName:PropTypes.string,\n  lastName:PropTypes.string,\n  country:PropTypes.string\n}\n\nexport default Person\n```\n\n`PropTypes` define the type of a prop. So each time, a value is passed through a prop, it gets validated for it\\'s type. If you pass a value through a prop with a different data type than it is specified in the PropTypes, an error message will be printed in the console of your browser.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q33. ***What is prop drilling and how can you avoid it?***\n\nReact passes data to child components via props from top to bottom. While there are few props or child components, it is easy to manage and pass down data. But when the application grows, and want to pass data from the top level component to a 3rd or 4th level level component but we end up passing these data to components on each level of the tree. This is called **Prop-drilling**.\n\n**Context API**  \n\nThe Context API solves some of these prop drilling problems. It let pass data to all of the components in the tree without writing them manually in each of them. Shared data can be anything: state, functions, objects, we name it, and it is accessible to all nested levels that are in the scope of the context.\n\n*Example*:\n\n```js\nimport React from \"react\"\nimport ReactDOM from \"react-dom\"\n\n// Create a Context\nconst NumberContext = React.createContext()\n// It returns an object with 2 values:\n// { Provider, Consumer }\n\nfunction App() {\n  // Use the Provider to make a value available to all\n  // children and grandchildren\n  return (\n    \u003cNumberContext.Provider value={10}\u003e\n      \u003cdiv\u003e\n        \u003cDisplay /\u003e\n      \u003c/div\u003e\n    \u003c/NumberContext.Provider\u003e\n  )\n}\n\nfunction Display() {\n  const value = useContext(NumberContext)\n  return \u003cdiv\u003eThe answer is {value}.\u003c/div\u003e\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q34. ***If you wanted a component to perform an action only once when the component initially rendered - how would you achieve this in react?***\n\nThe `componentDidMount()` lifecycle hook can be used with class components.\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```\nAny actions defined within a `componentDidMount()` lifecycle hook are called only once when the component is first mounted.\n\nThe `useEffect()` hook can be used with function components.\n```js\nconst Homepage = () =\u003e {\n  useEffect(() =\u003e {\n    trackPageView('Homepage')\n  }, [])\n  \n  return \u003cdiv\u003eHomepage\u003c/div\u003e\n}\n```\nThe `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. The  example above shows how passing an empty array can result in similar behaviour to the `componentDidMount()` hook within a function component.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q35. ***How can automated tooling be used to improve the accessibility of a React application?***\n\nThere are two main categories of automated tools that can be used to identify accessibility issues:\n\n**Static Analysis Tools**\n\nLinting tools like `ESLint` can be used with plugins such as `eslint-plugin-jsx-a11y` to analyse React projects at a component level. Static analysis tools run very quickly, so they bring a good benefit at a low cost.\n\n**Browser Tools**  \n\nBrowser accessibility tools such as `aXe` and `Google Lighthouse` perform automated accessibility at the app level. This can discover more real-world issues, because a browser is used to simulate the way that a user interacts with a website.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q36. ***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\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```\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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q37. ***Why should not we update the state directly?***\n\nThe `setState()` does not immediately mutate `this.state()` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.\n\nThere is no guarantee of synchronous operation of calls to `setState()` and calls may be batched for performance gains.\n\nThe `setState()` will always trigger a re-render unless conditional rendering logic is implemented in `shouldComponentUpdate()`. If mutable objects are being used and the logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders.\n\nBasically, if we modify `this.state()` directly, we create a situation where those modifications might get overwritten.\n\n*Example*:\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      list: [\n        { id: '1', age: 42 },\n        { id: '2', age: 33 },\n        { id: '3', age: 68 },\n      ],\n    }\n  }\n\n  onRemoveItem = id =\u003e {\n    this.setState(state =\u003e {\n      const list = state.list.filter(item =\u003e item.id !== id)\n\n      return {\n        list,\n      }\n    })\n  }\n\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cul\u003e\n          {this.state.list.map(item =\u003e (\n            \u003cli key={item.id}\u003e\n              The person is {item.age} years old.\n              \u003cbutton\n                type=\"button\"\n                onClick={() =\u003e this.onRemoveItem(item.id)}\n              \u003e\n                Remove\n              \u003c/button\u003e\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default App\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q38. ***What do these three dots (...) in React do?***\n\nThe ES6 Spread operator or Rest Parameters is use to pass `props` to a React component. Let us take an example for a component that expects two props:\n\n```js\nfunction App() {\n  return \u003cHello firstName=\"Alex\" lastName=\"K\" /\u003e\n}\n```\nUsing the Spread operator, it become like this\n\n```js\nfunction App() {\n  const props = {firstName: 'Alex', lastName: 'K'}\n  return \u003cHello {...props} /\u003e\n}\n```\n\nWhen we use the `...props` syntax, actaully it expand the props object from the parent component, which means all its attributes are passed down the child component that may not need them all. This will make things like debugging harder.\n\n**Using the Spread Operator with setState() for Setting the Nested State**\n\nlet us suppose we have a state with a nested object in our component:\n\n```js\nthis.state = {\n  stateObj: {\n    attr1: '',\n    attr2: '',\n  },\n}\n```\nWe can use the Spread syntax to update the nested state object.\n\n```js\nthis.setState(state =\u003e ({\n  person: {\n    ...state.stateObj,\n    attr1: 'value1',\n    attr2: 'value2',\n  },\n}))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q39. ***What are React Hooks? What are advantages of using React Hooks?***\n\nReact Hooks are in-built functions that allow to use **state** and **lifecycle** methods inside functional components, they also work together with existing code, so they can easily be adopted into a codebase.\n\n**Rules of Hooks**\n\n* Make sure to not use Hooks inside loops, conditions, or nested functions\n* Only use Hooks from inside React Functions\n\n**Built-in Hooks**\n\n*Basic Hooks*\n\n* useState()\n* useEffect()\n* useContext()\n\n*Additional Hooks*\n\n* useReducer()\n* useCallback()\n* useMemo()\n* useRef()\n* useImperativeHandle()\n* useLayoutEffect()\n* useDebugValue()\n\n**React Hooks advantages**  \n\n* Hooks are easier to work with and to test (as separated functions from React components*) and make the code look cleaner, easier to read — a related logic can be tightly coupled in a custom hook.\n* Hooks allow to do by breaking the logic between components into small functions and using them inside the components.\n* Improved code reuse\n* Better code composition\n* Better defaults\n* Sharing non-visual logic with the use of custom hooks\n* Flexibility in moving up and down the components tree.\n\n*Example*: using classes\n\n```js\nimport React, { Component } from 'react'\n\nclass App extends Component {\n  constuctor(props) {\n    super(props)\n\n    this.state = {\n      isButtonClicked: false,\n    }\n    this.handleClick = this.handleClick.bind(this)\n  }\n\n  handleClick() {\n    this.setState((prevState) =\u003e ({\n      isButtonClicked: !prevState.isButtonClicked,\n    }))\n  }\n}\n```\n\n*Example*: using React Hooks\n\n```js\nimport React, { useState } from 'react'\n\nconst App = () =\u003e {\n  const [isButtonClicked, setIsButtonClickedStatus] = useState(false)\n  \n  return (\n    \u003cbutton\n      onClick={() =\u003e setIsButtonClickedStatus(!isButtonClicked)}\n    \u003e\n      {isButtonClicked ? 'Clicked' : 'Click me, please'}\n    \u003c/button\u003e\n  )\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q40. ***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```bash\nnpm install prop-types --save-dev\n```\n\n*Example*:\n\n```js\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nApp.defaultProps = {\n   propBool: true,\n   propArray: [1, 2, 3, 4, 5],\n   propNumber: 100,\n   propString: \"Hello React!\"\n}\n\nclass App extends React.Component {\n\n   render() {\n      return (\n         \u003cfragment\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/fragment\u003e\n      )\n   }\n}\n\nApp.propTypes = {\n   propBool: PropTypes.bool.isRequired,\n   propArray: PropTypes.array.isRequired,\n   propNumber: PropTypes.number,\n   propString: PropTypes.string,\n}\n\nexport default App\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q41. ***What is the difference between using constructor vs getInitialState in React?***\n\nThe two approaches are not interchangeable. You should initialize state in the `constructor()` when using ES6 classes, and define the `getInitialState()` method when using React.createClass.\n\n```js\nimport React from 'react'\n\nclass MyComponent extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = { /* initial state */ }\n  }\n}\n```\n\nis equivalent to\n\n```js\nvar MyComponent = React.createClass({\n  getInitialState() {\n    return { /* initial state */ }\n  },\n})\n```\n\nThe `getInitialState()` is used with `React.createClass` and `constructor()` is used with `React.Component`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q42. ***How to conditionally add attributes to React components?***\n\nInline conditionals in attribute props\n\n```js\nimport React from 'react'\n\nfunction App() {\n\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\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q43. ***Do Hooks replace render props and higher-order components?***\n\n**React Hooks**\n\nHooks were designed to replace `class` and provide another great alternative to compose behavior into your components. Higher Order Components are also useful for composing behavior. Hooks encapsulate the functionality to easily reusable functions\n\n```js\nconst [active, setActive] = useState(defaultActive)\n```\n\nThere are few build-in Hooks\n\n```js\nimport {\n  useState,\n  useReducer,\n  useEffect,\n  useCallback,\n  useMemo,\n  useRef,\n  ...\n} from 'react'\n```\n\n**Higher Order Components**\n\nA Higher Order Component (HOC) is a component that takes a component and returns a component. HOCs are composable using point-free, declarative function composition.\n\n*Example*: logger API\n\n```js\nimport React, { useEffect } from 'react'\n\nconst withLogging = Component =\u003e props =\u003e {\n  useEffect(() =\u003e {\n    fetch(`/logger?location=${ window.location}`)\n  }, [])\n  return \u003cComponent {...props } /\u003e\n}\nexport default withLogging\n```\n\nTo use it, you can mix it into an HOC that you\\’ll wrap around every page:\n\n```js\nimport React from 'react'\nimport withAuth from './with-auth.js'\nimport withLogging from './with-logging.js'\nimport withLayout from './with-layout.js'\n\nconst page = compose(\n  withRedux,\n  withAuth,\n  withLogging,\n  withLayout('default'),\n)\nexport default page\n```\n\nTo use this for a page\n\n```js\nimport page from '../hocs/page.js'\nimport MyPageComponent from './my-page-component.js'\n\nexport default page(MyPageComponent)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q44. ***How to optimize React Performance?***\n\nReact uses many techniques to minimize the number of DOM operations for us already. For many applications, if you are using the production build, you may already meet or surpass your performance expectations. Nevertheless, there are several ways you can speed up your application.\n\n**1. React DevTools Profiler**\n\nExperience performance problems with a specific component, the React DevTools Profiler is usually the first place to look.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/react-dev-tools.png\"  alt=\"React DevTools\" /\u003e\n\u003c/p\u003e\n\n**2. Using `shouldComponentUpdate()` method**\n\nBy default, React will render the virtual DOM and compare the difference for every component in the tree for any change in its props or state. But that is obviously not reasonable. As our app grows, attempting to re-render and compare the entire virtual DOM at every action will eventually slow the whole thing down.\n\nReact provides a simple lifecycle method to indicate if a component needs re-rendering and that is, shouldComponentUpdate which is triggered before the re-rendering process starts. The default implementation of this function returns true.\n\n```js\nshouldComponentUpdate(nextProps, nextState) {\n  return true\n}\n```\n\nWhen this function returns true for any component, it allows the render differentiating process to be triggered. This gives us the power of controlling the render differentiating process. Suppose we need to prevent a component from being re-rendered, we need simply to return false from that function. As we can see from the implementation of the method, we can compare the current and next props and state to determine whether a re-render is necessary:\n\n```js\nshouldComponentUpdate(nextProps, nextState) {\n  return nextProps.id !== this.props.id\n}\n```\n\n**3. Using Pure Components**\n\nPure Components in React are the components which do not re-renders when the value of `state` and `props` has been updated with the same values. If the value of the previous `state` or `props` and the new `state` or `props` is the same, the component is not re-rendered. Pure Components restricts the re-rendering ensuring the higher performance of the Component.\n\n**4. Using React.memo**\n\nReact.memo is a higher order component. It\\'s similar to `React.PureComponent` but for function components instead of classes.\n\n```js\nconst MyComponent = React.memo(function MyComponent(props) {\n  /* render using props */\n})\n```\n\nIf your function component renders the same result given the same props, you can wrap it in a call to `React.memo` for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.\n\n`React.memo` only checks for `prop` changes. If your function component wrapped in `React.memo` has a `useState` or `useContext` Hook in its implementation, it will still rerender when `state` or `context` change.\n\n**5. Virtualizing Long Lists**\n\nIn order to address the issue with our long chat feed, the React team recommends a technique called windowing. This technique only renders the portion of the list that is visible to the user (+/- a given offset) in order to reduce the time to render. As the user scrolls, new list items are retrieved and rendered. `react-window` and `react-virtualized` are two libraries that provide components to help with list virtualization.\n\n**[[Read More](https://reactjs.org/docs/optimizing-performance.html)]**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q45. ***When would you use StrictMode component in React?***\n\n`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. Strict mode checks are run in development mode only; they do not impact the production build.\n\n```js\nimport React from 'react'\n\nexport default function App() {\n  return (\n    \u003cFragment\u003e\n      \u003cHeader /\u003e\n      \u003cReact.StrictMode\u003e\n        \u003cdiv\u003e\n          \u003cComponentOne /\u003e\n          \u003cComponentTwo /\u003e\n        \u003c/div\u003e\n      \u003c/React.StrictMode\u003e\n      \u003cFooter /\u003e\n    \u003c/Fragment\u003e\n  )\n}\n```\n\nIn the above example, strict mode checks will not be run against the `\u003cHeader\u003e` and `\u003cFooter\u003e` components. However, `\u003cComponentOne\u003e` and `\u003cComponentTwo\u003e`, as well as all of their descendants, will have the checks.\n\n`React.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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q46. ***How does React renderer work exactly when we call setState?***\n\nThe `state` allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule. Components defined as classes have some additional features. Local state is a feature available only to class Components.\n\nThe `setState()` is the API method provided with the library so that the user is able to define and manipulate state over time.\n`setState()` is the only legitimate way to update state after the initial state setup.\n\n*Example*:\n\n```js\nimport React, { Component } from 'react'\n\nclass Search extends Component {\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      searchString: ''\n    }\n  }\n}\n```\nwe are passing an empty string as a value and, to update the state of searchString, we have to call setState().\n\n```js\nsetState({ searchString: event.target.value })\n```\n\nHere, we are passing an object to setState(). The object contains the part of the state we want to update which, in this case, is the value of searchString. This is basically kicking off a process that React calls **reconciliation**. The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state.\n\nWhen the request to `setState()` is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the Search component\\'s UI should change in response to the state change by comparing it with the elements of the previous tree.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q47. ***How to avoid the need for binding in React?***\n\n**1. Use Arrow Function in Class Property**\n\nUsually when we want to access this inside a class method we would need to bind it to method like so:\n\n```js\nclass Button extends Component {\n  constructor(props) {\n    super(props)\n    this.state = { clicked: false }\n  }\n  handleClick = () =\u003e this.setState({ clicked: true })\n  render() {\n    return \u003cbutton onClick={this.handleClick}\u003eClick Me\u003c/button\u003e\n  }\n}\n```\nBinding `this` to `handleClick()` in the `constructor()` allows us to use `this.setState()` from Component inside `handleClick()`.\n\n**2. Bind in Render**\n\n```js\nonChange={this.handleChange.bind(this)}\n```\n\nThis approach is terse and clear, however, there are performance implications since the function is reallocated on every render.\n\n**3. Bind in Constructor**\n\nOne way to avoid binding in render is to bind in the constructor\n\n```js\nconstructor(props) {\n  super(props)\n  this.handleChange = this.handleChange.bind(this)\n}\n```\n\nThis is the approach currently recommended in the React docs for \"better performance in your application\".\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q48. ***How does the state differ from props in React?***\n\n**State**\n\nThis is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the `setState()` function.\n\n*Example*:\n\n```js\nclass AppComponent extends React.component {\n  state = {\n      msg : 'Hello World!'\n  }\n\n  render() {\n      return \u003cdiv\u003eMessage {this.state.msg}\u003c/div\u003e\n  }\n}\n```\n\n**Props**\n\nData passed in from a parent component. `props` are read-only in the child component that receives them. However, callback functions can also be passed, which can be executed inside the child to initiate an update.\n\n*Example*: The parent can pass a props by using this\n\n```js\n\u003cChildComponent color='red' /\u003e\n```\nInside the ChildComponent constructor we could access the props\n\n```js\nclass ChildComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    console.log(props.color)\n  }\n}\n```\n\nProps can be used to set the internal state based on a prop value in the constructor, like this\n\n```js\nclass ChildComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state.colorName = props.color\n  }\n}\n```\n\nProps should never be changed in a child component. Props are also used to allow child components to access methods defined in the parent component. This is a good way to centralize managing the state in the parent component, and avoid children to have the need to have their own state.\n\n**Difference between State and Props**\n\n|  Props                                          | State                            |\n|-------------------------------------------------|----------------------------------|\n|Props are read-only.                             |State changes can be asynchronous.|\n|Props allow to pass data from one component to other components as an argument.| State holds information about the components.|\n|Props can be accessed by the child component.    |State cannot be accessed by child components.|\n|Props are used to communicate between components.|States can be used for rendering dynamic changes with the component.|\n|Stateless component can have Props.              |Stateless components cannot have State.|\n|Props are external and controlled by whatever renders the component.| The State is internal and controlled by the React Component itself.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q49. ***How would you create a form in React?***\n\n**App.js**\n\n```js\nimport React, { Component } from \"react\"\nimport countries from \"./countries\"\nimport './App.css'\n\nexport default function App() {\n  const [email, setEmail] = React.useState(\"\")\n  const [password, setPassword] = React.useState(\"\")\n  const [country, setCountry] = React.useState(\"\")\n  const [acceptedTerms, setAcceptedTerms] = React.useState(false)\n\n  const handleSubmit = (event) =\u003e {\n    console.log(`\n      Email: ${email}\n      Password: ${password}\n      Country: ${country}\n      Accepted Terms: ${acceptedTerms}\n    `)\n    event.preventDefault()\n  }\n\n  return (\n    \u003cform onSubmit={handleSubmit}\u003e\n      \u003ch1\u003eCreate Account\u003c/h1\u003e\n\n      \u003clabel\u003e\n        Email:\n        \u003cinput\n          name=\"email\"\n          type=\"email\"\n          value={email}\n          onChange={e =\u003e setEmail(e.target.value)}\n          required /\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003e\n        Password:\n        \u003cinput\n          name=\"password\"\n          type=\"password\"\n          value={password}\n          onChange={e =\u003e setPassword(e.target.value)}\n          required /\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003e\n        Country:\n        \u003cselect\n          name=\"country\"\n          value={country}\n          onChange={e =\u003e setCountry(e.target.value)}\n          required\u003e\n          \u003coption key=\"\"\u003e\u003c/option\u003e\n          {countries.map(country =\u003e (\n            \u003coption key={country}\u003e{country}\u003c/option\u003e\n          ))}\n        \u003c/select\u003e\n      \u003c/label\u003e\n\n      \u003clabel\u003e\n        \u003cinput\n          name=\"acceptedTerms\"\n          type=\"checkbox\"\n          onChange={e =\u003e setAcceptedTerms(e.target.value)}\n          required /\u003e\n        I accept the terms of service\n      \u003c/label\u003e\n\n      \u003cbutton\u003eSubmit\u003c/button\u003e\n    \u003c/form\u003e\n  )\n}\n```\n\n**App.css**\n\n```css\n* {\n  box-sizing: border-box;\n}\n\nbody {\n  font-family: Lato;\n  height: 97vh;\n  width: 100%;\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  align-items: center;\n  background-color: #4A4E69;\n}\n\nform {\n  display: flex;\n  flex-direction: column;\n  width: 400px;\n  min-width: 100px;\n  min-height: 400px;\n  padding: 20px 40px 40px 40px;\n  border-radius: 6px;\n  box-shadow: 0px 8px 36px #222;\n  background-color: #fefefe;\n}\n\nform \u003e h1 {\n  display: flex;\n  justify-content: center;\n  font-family: \"Segoe UI\", \"Ubuntu\", \"Roboto\", \"Open Sans\", \"Helvetica Neue\", sans-serif;\n  font-size: 2em;\n  font-weight: lighter;\n  margin-top: 0.25em;\n  color: #222;\n  letter-spacing: 2px;\n}\n\n.info {\n  padding-bottom: 1em;\n  padding-left: 0.5em;\n  padding-right: 0.5em;\n}\n\nlabel {\n  margin-bottom: 0.5em;\n  color: #444;\n  font-weight: lighter;\n}\n\ninput {\n  display: flex;\n  flex-direction: column;\n  margin-bottom: 15px;\n  width: 100%;\n}\ninput, select {\n  padding: 10px 10px;\n  border-radius: 5px;\n  border: 1px solid #d6d1d5;\n  margin-top: 5px;\n}\nselect {\n  display: block;\n  width: 100%;\n  height: 35px;\n}\ninput[type=\"checkbox\"] {\n  display: inline-block;\n  width: auto;\n  margin-top: 2em;\n  margin-right: 10px;\n}\n\nbutton {\n  min-width: 100%;\n  cursor: pointer;\n  margin-right: 0.25em;\n  margin-top: 0.5em;\n  padding: \t0.938em;\n  border: none;\n  border-radius: 4px;\n  background-color: #22223B;\n  color: #fefefe;\n}\nbutton:hover {\n  background-color: #4A4E69;\n  color: #fefefe;\n}\n\n.error {\n  color:#db2269;\n  font-size: 0.5em;\n  display: relative;\n}\n\n.submit {\n  width: 100%;\n  display: flex;\n  flex-wrap: wrap;\n}\n```\n\n**Countries.js**\n\n```js\nexport default [\n  'Austria',\n  'Denmark',\n  'France',\n  'Germany',\n  'India',\n  'Italy',\n  'Poland',\n  'Russia',\n  'Sweden',\n  'United States'\n];\n```\n\nOutput:\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src='assets/react-form.png' alt='React Form' width='500px' /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q50. ***How to change the state of a child component from its parent in React?***\n\n**Using Props**\n\nWe will take two components, Parent and Child. And our Parent component will set the value depends on the Child Component. Child component holds the Input field and we are going to send the input field value to the Parent component.\n\n```js\nfunction Parent() {\n    const [value, setValue] = React.useState(\"\")\n\n    function handleChange(newValue) {\n      setValue(newValue)\n    }\n\n    // We pass a callback to Child\n    return \u003cChild value={value} onChange={handleChange} /\u003e\n}\n```\n\nAs you see that we set the onChange property to the Child component. Next step is to create the Child component.\n\n```js\nfunction Child(props) {\n    function handleChange(event) {\n        // Here, we invoke the callback with the new value\n        props.onChange(event.target.value)\n    }\n  \n    return \u003cinput value={props.value} onChange={handleChange} /\u003e\n}\n```\n\nOn the above codes, we have created function handleChange that will pass the value through props.onChange to our Parent component.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q51. ***What do you understand with the term polling in React?***\n\nUsing `setInterval()` inside React components allows us to execute a function or some code at specific intervals.\n\n```js\nuseEffect(() =\u003e {\n  const interval = setInterval(() =\u003e {\n    console.log('This will run every second!')\n  }, 1000)\n  return () =\u003e clearInterval(interval)\n}, [])\n```\n\nThe code above schedules a new interval to run every second inside of the useEffect Hook. This will schedule once the React component mounts for the first time. To properly clear the interval, we return `clearInterval()` from the `useEffect()` Hook, passing in the interval.\n\n**Using setInterval in React Components**\n\nTo schedule a new interval, we call the setInterval method inside of a React component, like so:\n\n```js\nimport React, { useState, useEffect } from 'react'\n\nconst IntervalExample = () =\u003e {\n  const [seconds, setSeconds] = useState(0)\n\n  useEffect(() =\u003e {\n    const interval = setInterval(() =\u003e {\n      setSeconds(seconds =\u003e seconds + 1)\n    }, 1000)\n    return () =\u003e clearInterval(interval)\n  }, [])\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cheader className=\"App-header\"\u003e\n        {seconds} seconds have elapsed since mounting.\n      \u003c/header\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default IntervalExample\n```\n\nThe example above shows a React component, IntervalExample, scheduling a new interval once it mounts to the DOM. The interval increments the seconds state value by one, every second.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q52. ***What is the difference between Element, Component and Component instance in React?***\n\nA React Component is a template. A blueprint. A global definition. This can be either a function or a class (with a render function).\n\nA React Element is what gets returned from components. It is an object that virtually describes the DOM nodes that a component represents. With a function component, this element is the object that the function returns. With a class component, the element is the object that the component\\'s render function returns. React elements are not what we see in the browser. They are just objects in memory and we can not change anything about them.\n\n*Example*:\n\n```js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport './index.css'\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\n\nconsole.log('This is an element:', element)\n\nReactDOM.render(\n  element,\n  document.getElementById('root')\n)\n```\n\n**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 (or depending on the type an HTML tag) to be created should look like.\n\nA React Element that describes a React Component doesn't know to which DOM node it is eventually rendered - this association is abstracted and will be resolved while rendering.\n\nReact Elements may contain child elements and thus are capable of forming element trees, which represent the Virtual DOM tree.\n\n**React Components and React Component Instances**\n\nA custom React Component is either created by `React.createClass` or by extending `React.Component` (ES2015). 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. Please note that you never construct React Component Instances yourself but let React create it for you.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q53. ***In which lifecycle event do you make AJAX requests in React?***\n\nAccording to official React docs, the recommended place to do Ajax requests is in `componentDidMount()` which is a lifecycle method that runs after the React component has been mounted to the DOM. This is so you can use `setState()` to update your component when the data is retrieved.\n\n*Example*:\n\n```js\nimport React from 'react'\n\nclass MyComponent extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {\n      error: null,\n      isLoaded: false,\n      items: []\n    }\n  }\n\n  componentDidMount() {\n    fetch(\"https://api.example.com/items\")\n      .then(res =\u003e res.json())\n      .then(\n        (result) =\u003e {\n          this.setState({\n            isLoaded: true,\n            items: result.items\n          })\n        },\n        // Note: it's important to handle errors here\n        // instead of a catch() block so that we don't swallow\n        // exceptions from actual bugs in components.\n        (error) =\u003e {\n          this.setState({\n            isLoaded: true,\n            error\n          })\n        }\n      )\n  }\n\n  render() {\n    const { error, isLoaded, items } = this.state\n    if (error) {\n      return \u003cdiv\u003eError: {error.message}\u003c/div\u003e\n    } else if (!isLoaded) {\n      return \u003cdiv\u003eLoading...\u003c/div\u003e\n    } else {\n      return (\n        \u003cul\u003e\n          {items.map(item =\u003e (\n            \u003cli key={item.name}\u003e\n              {item.name} {item.price}\n            \u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      )\n    }\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q54. ***What is meant by event handling in React?***\n\nHandling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:\n\n* React events are named using camelCase, rather than lowercase.\n* With JSX you pass a function as the event handler, rather than a string.\n\n```js\nclass Toggle extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {isToggleOn: true}\n\n    // This binding is necessary to make `this` work in the callback\n    this.handleClick = this.handleClick.bind(this)\n  }\n\n  handleClick() {\n    this.setState(state =\u003e ({\n      isToggleOn: !state.isToggleOn\n    }))\n  }\n\n  render() {\n    return (\n      \u003cbutton onClick={this.handleClick}\u003e\n        {this.state.isToggleOn ? 'ON' : 'OFF'}\n      \u003c/button\u003e\n    )\n  }\n}\n\nReactDOM.render(\n  \u003cToggle /\u003e,\n  document.getElementById('root')\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q55. ***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/h1\u003e\n    \u003c/div\u003e\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q56. ***Explain DOM diffing?***\n\n**Document Object Model**\n\nThe DOM (Document Object Model) is an interface that represents an HTML document in a tree-like structure with nodes. This structure allows the document to be traversed and modified by programmers with each node being represented as an object. The DOM is created by the browser when\na web page is loaded.\n\n**React\\'s \"Virtual DOM\"**\n\nThe \"Virtual DOM\" is very similar to the real DOM, in that it is a tree-like structure kept in-memory, where React elements are represented as objects. This tree has many of the same properties as the real DOM without the power to change what is on the screen. It is a javascript object representing components in your application which can be updated quickly and efficiently by React.\n\nWhen a JSX element is rendered or the state of an element changes, a new Virtual DOM tree is created. The function responsible for the creation of this tree is React\\'s render() function. This is a fast process because the virtual DOM tree is just a javascript object and the UI will not be re-painted based on this new tree.\n\n**DOM Diffing**\n\nOnce the Virtual DOM is created, React compares this new representation with a snapshot of the previous version of the virtual DOM to see exactly which elements have changed.\n\nOnce the difference is known, React updates only those objects that differ on the actual DOM and the browser re-paints the screen. The next time state or props changes for a component in the application, a new virtual DOM tree of React elements will be created and the process will repeat.\n\nThe process of checking the difference between the new Virtual DOM tree and the old Virtual DOM tree is called **diffing**. Diffing is accomplished by a **heuristic O(n)** algorithm. During this process, React will deduce the minimum number of steps needed to update the real DOM, eliminating unnecessary costly changes. This process is also referred to as **reconciliation**.\n\nReact implements a heuristic O(n) algorithm based on two assumptions:\n\n1. Two elements of different types will produce different trees.\n1. The developer can hint at which child elements may be stable across different renders with a key prop.\"\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q57. ***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=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q58. ***What is the purpose of render() function in React?***\n\nAll React applications start at a root DOM node that marks the portion of the DOM that will be managed by React. When React is called to render the component tree it will first need the JSX in code to be converted into pure JavaScript. `render` function is part of the react component lifecyle where `ReactDOM` is the class object which exposes a method called `render` which is used to render the React JSX content into DOM.\n\nGenerally you would use `ReactDOM.render()` once in your App to render the top level component, all other components will be children to the top level component. A react component goes though a number of mounting and updating lifecycle method and decides to render the data in the render function. Any JSX code that you write in `render()` method is converted to `React.createElement(tag, props, children)` before it is rendered into the DOM.\n\n```js\n// App.js\nimport React from 'react'\nimport './App.css'\n\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      Hello World !\n    \u003c/div\u003e\n  )\n}\n\nexport default App\n```\n\n```js\n// index.js\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport './index.css'\nimport App from './App/App'\n\nReactDOM.render(\n  \u003cReact.StrictMode\u003e\n    \u003cApp /\u003e\n  \u003c/React.StrictMode\u003e,\n  document.getElementById('root')\n)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q59. ***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\nA React component can be either **stateful** or **stateless**. Stateful components are of the class type, while stateless components are of the function type.\n\n**Stateless Component**\n\n```js\nimport React from 'react'\n\nconst ExampleComponent = (props) =\u003e {\n    return (\u003ch1\u003eWelcome to React!\u003c/h1\u003e)\n}\n\nexport default class App extends React.Component {\n  render() {\n    return (\n      \u003cdiv\u003e\n        \u003cExampleComponent/\u003e\n      \u003c/div\u003e\n    )\n  }\n}\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.\n\n**Stateful Component**\n\n```js\nimport React from 'react'\n\nclass ExampleComponent extends React.Component {\n\n  constructor(props) {\n    super(props)\n    this.state = {\n      heading: \"This is ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faakashdeveloper%2Freact-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faakashdeveloper%2Freact-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faakashdeveloper%2Freact-interview-questions/lists"}