React 3of4 Flashcards

#201-300

1
Q

<p></p>

<p></p>

<p>Why React tab is not showing up in DevTools?</p>

A

<p></p>

<p></p>

<p>When the page loads, React DevTools sets a global named \_\_REACT_DEVTOOLS_GLOBAL_HOOK\_\_, then React communicates with that hook during initialization. If the website is not using React or if React fails to communicate with DevTools then it won't show up the tab.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

<p></p>

<p></p>

<p>What are Styled Components?</p>

A

<p></p>

<p></p>

<p>styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

<p></p>

<p></p>

<p>Give an example of Styled Components?</p>

A

<p></p>

<p></p>

<p>Lets create and components with specific styles for each.
<br></br>
<br></br>import React from 'react'
<br></br>import styled from 'styled-components'
<br></br>
<br></br>// Create a component that renders an </p>

<h1> which is centered, red and sized at 1.5em
<br></br>const Title = styled.h1`
<br></br> font-size: 1.5em;
<br></br> text-align: center;
<br></br> color: palevioletred;
<br></br>`
<br></br>
<br></br>// Create a component that renders a with some padding and a papayawhip background
<br></br>const Wrapper = styled.section`
<br></br> padding: 4em;
<br></br> background: papayawhip;
<br></br>`
<br></br>These two variables, Title and Wrapper, are now components that you can render just like any other react component.
<br></br>
<br></br>
<br></br> {'Lets start first styled component!'}
<br></br></h1>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

<p></p>

<p></p>

<p>What is Relay?</p>

A

<p></p>

<p></p>

<p>Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

<p></p>

<p></p>

<p>How to use TypeScript in create-react-app application?</p>

A

<p></p>

<p></p>

<p>Starting from react-scripts@2.1.0 or higher, there is a built-in support for typescript. i.e, create-react-app now supports typescript natively. You can just pass --typescript option as below
<br></br>
<br></br>npx create-react-app my-app --typescript
<br></br>
<br></br># or
<br></br>
<br></br>yarn create react-app my-app --typescript
<br></br>But for lower versions of react scripts, just supply --scripts-version option as react-scripts-ts while you create a new project. react-scripts-ts is a set of adjustments to take the standard create-react-app project pipeline and bring TypeScript into the mix.
<br></br>
<br></br>Now the project layout should look like the following:
<br></br>
<br></br>my-app/
<br></br>├─ .gitignore
<br></br>├─ images.d.ts
<br></br>├─ node_modules/
<br></br>├─ public/
<br></br>├─ src/
<br></br>│ └─ ...
<br></br>├─ package.json
<br></br>├─ tsconfig.json
<br></br>├─ tsconfig.prod.json
<br></br>├─ tsconfig.test.json
<br></br>└─ tslint.json</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

<p></p>

<p></p>

<p>What are the main features of Reselect library?</p>

A

<p></p>

<p></p>

<p>Let's see the main features of Reselect library,
<br></br>
<br></br>[1] Selectors can compute derived data, allowing Redux to store the minimal possible state.
<br></br>[2] Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
<br></br>[3] Selectors are composable. They can be used as input to other selectors.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

<p></p>

<p></p>

<p>Give an example of Reselect usage?</p>

A

<p></p>

<p></p>

<p>Let's take calculations and different amounts of a shipment order with the simplified usage of Reselect:
<br></br>
<br></br>import { createSelector } from 'reselect'
<br></br>
<br></br>const shopItemsSelector = state => state.shop.items
<br></br>const taxPercentSelector = state => state.shop.taxPercent
<br></br>
<br></br>const subtotalSelector = createSelector(
<br></br> shopItemsSelector,
<br></br> items => items.reduce((acc, item) => acc + item.value, 0)
<br></br>)
<br></br>
<br></br>const taxSelector = createSelector(
<br></br> subtotalSelector,
<br></br> taxPercentSelector,
<br></br> (subtotal, taxPercent) => subtotal * (taxPercent / 100)
<br></br>)
<br></br>
<br></br>export const totalSelector = createSelector(
<br></br> subtotalSelector,
<br></br> taxSelector,
<br></br> (subtotal, tax) => ({ total: subtotal + tax })
<br></br>)
<br></br>
<br></br>let exampleState = {
<br></br> shop: {
<br></br> taxPercent: 8,
<br></br> items: [
<br></br> { name: 'apple', value: 1.20 },
<br></br> { name: 'orange', value: 0.95 },
<br></br> ]
<br></br> }
<br></br>}
<br></br>
<br></br>console.log(subtotalSelector(exampleState)) // 2.15
<br></br>console.log(taxSelector(exampleState)) // 0.172
<br></br>console.log(totalSelector(exampleState)) // { total: 2.322 }</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

<p></p>

<p></p>

<p>-</p>

A

<p></p>

<p></p>

<p>-</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

<p></p>

<p></p>

<p>Does the statics object work with ES6 classes in React?</p>

A

<p></p>

<p></p>

<p>No, statics only works with React.createClass():
<br></br>
<br></br>someComponent= React.createClass({
<br></br> statics: {
<br></br> someMethod: function() {
<br></br> // ..
<br></br> }
<br></br> }
<br></br>})
<br></br>But you can write statics inside ES6+ classes as below,
<br></br>
<br></br>class Component extends React.Component {
<br></br> static propTypes = {
<br></br> // ...
<br></br> }
<br></br>
<br></br> static someMethod() {
<br></br> // ...
<br></br> }
<br></br>}
<br></br>or writing them outside class as below,
<br></br>
<br></br>class Component extends React.Component {
<br></br> ....
<br></br>}
<br></br>
<br></br>Component.propTypes = {...}
<br></br>Component.someMethod = function(){....}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

<p></p>

<p></p>

<p>Can Redux only be used with React?</p>

A

<p></p>

<p></p>

<p>Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

<p></p>

<p></p>

<p>Do you need to have a particular build tool to use Redux?</p>

A

<p></p>

<p></p>

<p>Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

<p></p>

<p></p>

<p>How Redux Form initialValues get updated from state?</p>

A

<p></p>

<p></p>

<p>You need to add enableReinitialize : true setting.
<br></br>
<br></br>const InitializeFromStateForm = reduxForm({
<br></br> form: 'initializeFromState',
<br></br> enableReinitialize : true
<br></br>})(UserEdit)
<br></br>
<br></br>If your initialValues prop gets updated, your form will update too.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

<p></p>

<p></p>

<p>How React PropTypes allow different types for one prop?</p>

A

<p></p>

<p></p>

<p>You can use oneOfType() method of PropTypes.
<br></br>
<br></br>For example, the height property can be defined with either string or number type as below:
<br></br>
<br></br>Component.propTypes = {
<br></br> size: PropTypes.oneOfType([
<br></br> PropTypes.string,
<br></br> PropTypes.number
<br></br> ])
<br></br>}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

<p></p>

<p></p>

<p>Can I import an SVG file as react component?</p>

A

<p></p>

<p></p>

<p>You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.
<br></br>
<br></br>import { ReactComponent as Logo } from './logo.svg'
<br></br>
<br></br>const App = () => (
<br></br> </p>

<div>
<br></br> {/* Logo is an actual react component */}
<br></br>
<br></br> </div>

<br></br>)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

<p></p>

<p></p>

<p>Why are inline ref callbacks or functions not recommended?</p>

A

<p></p>

<p></p>

<p>If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.
<br></br>
<br></br>class UserForm extends Component {
<br></br> handleSubmit = () => {
<br></br> console.log("Input Value is: ", this.input.value)
<br></br> }
<br></br>
<br></br>
<br></br> render () {
<br></br> return (
<br></br>
<br></br> this.input = input} /> // Access DOM input in handle submit
<br></br> Submit
<br></br>
<br></br> )
<br></br> }
<br></br>}
<br></br>But our expectation is for the ref callback to get called once, when the component mounts. One quick fix is to use the ES7 class property syntax to define the function
<br></br>
<br></br>class UserForm extends Component {
<br></br> handleSubmit = () => {
<br></br> console.log("Input Value is: ", this.input.value)
<br></br> }
<br></br>
<br></br> setSearchInput = (input) => {
<br></br> this.input = input
<br></br> }
<br></br>
<br></br> render () {
<br></br> return (
<br></br>
<br></br> // Access DOM input in handle submit
<br></br> Submit
<br></br>
<br></br> )
<br></br> }
<br></br>}
<br></br>**Note:** In React v16.3,</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

<p></p>

<p></p>

<p>What is render hijacking in react?</p>

A

<p></p>

<p></p>

<p>The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

<p></p>

<p></p>

<p>What are HOC factory implementations?</p>

A

<p></p>

<p></p>

<p>There are two main ways of implementing HOCs in React.
<br></br>
<br></br>Props Proxy (PP) and
<br></br>Inheritance Inversion (II).
<br></br>But they follow different approaches for manipulating the WrappedComponent.
<br></br>
<br></br>Props Proxy
<br></br>
<br></br>In this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent. We also pass through the props that the HOC receives, hence the name Props Proxy.
<br></br>
<br></br>function ppHOC(WrappedComponent) {
<br></br> return class PP extends React.Component {
<br></br> render() {
<br></br> return
<br></br> }
<br></br> }
<br></br>}
<br></br>Inheritance Inversion
<br></br>
<br></br>In this approach, the returned HOC class (Enhancer) extends the WrappedComponent. It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively extended by the Enhancer. In this way the relationship between them seems inverse.
<br></br>
<br></br>function iiHOC(WrappedComponent) {
<br></br> return class Enhancer extends WrappedComponent {
<br></br> render() {
<br></br> return super.render()
<br></br> }
<br></br> }
<br></br>}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

<p></p>

<p></p>

<p>How to pass numbers to React component?</p>

A

<p></p>

<p></p>

<p>You should be passing the numbers via curly braces({}) where as strings in quotes
<br></br>
<br></br> React.render(, document.getElementById('container'));</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

<p></p>

<p></p>

<p>Do I need to keep all my state into Redux? Should I ever use react internal state?</p>

A

<p></p>

<p></p>

<p>It is up to the developer's decision, i.e., it is developer's job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.
<br></br>
<br></br>Below are the thumb rules to determine what kind of data should be put into Redux
<br></br>
<br></br>[1] Do other parts of the application care about this data?
<br></br>[2] Do you need to be able to create further derived data based on this original data?
<br></br>[3] Is the same data being used to drive multiple components?
<br></br>[4] Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
<br></br>[5] Do you want to cache the data (i.e, use what's in state if it's already there instead of re-requesting it)?</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

<p></p>

<p></p>

<p>What is the purpose of registerServiceWorker in React?</p>

A

<p></p>

<p></p>

<p>React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that's what you should know about service worker for now. It's all about adding offline capabilities to your site.
<br></br>
<br></br> import React from 'react';
<br></br> import ReactDOM from 'react-dom';
<br></br> import App from './App';
<br></br> import registerServiceWorker from './registerServiceWorker';
<br></br>
<br></br> ReactDOM.render(, document.getElementById('root'));
<br></br> registerServiceWorker();</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

<p></p>

<p></p>

<p>What is React memo function?</p>

A

<p></p>

<p></p>

<p>Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.
<br></br>
<br></br>const MyComponent = React.memo(function MyComponent(props) {
<br></br> /* only rerenders if props change */
<br></br>});</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

<p></p>

<p></p>

<p>What is React lazy function?</p>

A

<p></p>

<p></p>

<p>The React.lazy function lets you render a dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.
<br></br>
<br></br>const OtherComponent = React.lazy(() => import('./OtherComponent'));
<br></br>
<br></br>function MyComponent() {
<br></br> return (
<br></br> </p>

<div>
<br></br>
<br></br> </div>

<br></br> );
<br></br>}
<br></br>Note: React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we still recommend React Loadable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

<p></p>

<p></p>

<p>How to prevent unnecessary updates using setState?</p>

A

<p></p>

<p></p>

<p>You can compare the current value of the state with an existing state value and decide whether to rerender the page or not. If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value.
<br></br>
<br></br>For example, the user profile information is conditionally rendered as follows,
<br></br>
<br></br>getUserProfile = user => {
<br></br> const latestAddress = user.address;
<br></br> this.setState(state => {
<br></br> if (state.address === latestAddress) {
<br></br> return null;
<br></br> } else {
<br></br> return { title: latestAddress };
<br></br> }
<br></br> });
<br></br>};</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

<p></p>

<p></p>

<p>How do you render Array, Strings and Numbers in React 16 Version?</p>

A

<p></p>

<p></p>

<p>Arrays: Unlike older releases, you don't need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array.
<br></br>
<br></br>For example, let us take the below list of developers,
<br></br>
<br></br>const ReactJSDevs = () => {
<br></br> return [
<br></br> </p>

<li>John</li>

,
<br></br> <li>Jackie</li>,
<br></br> <li>Jordan</li>
<br></br> ];
<br></br>}
<br></br>You can also merge this array of items in another array component.
<br></br>
<br></br>const JSDevs = () => {
<br></br> return (
<br></br> <ul>
<br></br> <li>Brad</li>
<br></br> <li>Brodge</li>
<br></br>
<br></br> <li>Brandon</li>
<br></br> </ul>
<br></br> );
<br></br>}
<br></br>Strings and Numbers: You can also return string and number type from the render method.
<br></br>
<br></br>render() {
<br></br> return ‘Welcome to ReactJS questions’;
<br></br>}
<br></br>// Number
<br></br>render() {
<br></br> return 2018;
<br></br>}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

<p></p>

<p></p>

<p>How to use class field declarations syntax in React classes?</p>

A

<p></p>

<p></p>

<p>React Class Components can be made much more concise using the class field declarations. You can initialize the local state without using the constructor and declare class methods by using arrow functions without the extra need to bind them.
<br></br>
<br></br>Let's take a counter example to demonstrate class field declarations for state without using constructor and methods without binding,
<br></br>
<br></br>class Counter extends Component {
<br></br> state = { value: 0 };
<br></br>
<br></br> handleIncrement = () => {
<br></br> this.setState(prevState => ({
<br></br> value: prevState.value + 1
<br></br> }));
<br></br> };
<br></br>
<br></br> handleDecrement = () => {
<br></br> this.setState(prevState => ({
<br></br> value: prevState.value - 1
<br></br> }));
<br></br> };
<br></br>
<br></br> render() {
<br></br> return (
<br></br> </p>

<div>
<br></br> {this.state.value}
<br></br>
<br></br> +
<br></br> -
<br></br> </div>

<br></br> )
<br></br> }
<br></br>}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

<p></p>

<p></p>

<p>What are hooks?</p>

A

<p></p>

<p></p>

<p>Hooks is a new feature(React 16.8) that lets you use state and other React features without writing a class.
<br></br>
<br></br>Let's see an example of useState hook:
<br></br>
<br></br>import { useState } from 'react';
<br></br>
<br></br>function Example() {
<br></br> // Declare a new state variable, which we'll call "count"
<br></br> const [count, setCount] = useState(0);
<br></br>
<br></br> return (
<br></br> </p>

<div>
<br></br> <p>You clicked {count} times</p>
<br></br> setCount(count + 1)}>
<br></br> Click me
<br></br>
<br></br> </div>

<br></br> );
<br></br>}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

<p></p>

<p></p>

<p>What rules need to be followed for hooks?</p>

A

<p></p>

<p></p>

<p>You need to follow two rules in order to use hooks,
<br></br>
<br></br>[1] Call Hooks only at the top level of your react functions. i.e, You shouldn’t call Hooks inside loops, conditions, or nested functions. This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple useState and useEffect calls.
<br></br>
<br></br>[2] Call Hooks from React Functions only. i.e, You shouldn’t call Hooks from regular JavaScript functions.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

<p></p>

<p></p>

<p>How to ensure hooks followed the rules in your project?</p>

A

<p></p>

<p></p>

<p>React team released an ESLint plugin called eslint-plugin-react-hooks that enforces these two rules. You can add this plugin to your project using the below command,
<br></br>
<br></br>npm install eslint-plugin-react-hooks@next
<br></br>
<br></br>And apply the below config in your ESLint config file,
<br></br>// Your ESLint configuration
<br></br>{
<br></br> "plugins": [
<br></br> // ...
<br></br> "react-hooks"
<br></br> ],
<br></br> "rules": {
<br></br> // ...
<br></br> "react-hooks/rules-of-hooks": "error"
<br></br> }
<br></br>}
<br></br>
<br></br>Note: This plugin is intended to use in Create React App by default.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

<p></p>

<p></p>

<p>What are the differences between Flux and Redux?</p>

A

<p></p>

<p></p>

<p>Below are the major differences between Flux and Redux</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

<p></p>

<p>What are the benefits of React Router V4?</p>

A

<p></p>

<p>Below are the main benefits of React Router V4 module,
<br></br>
<br></br>In React Router v4(version 4), the API is completely about components. A router can be visualized as a single component() which wraps specific child router components().
<br></br>You don't need to manually set history. The router module will take care history by wrapping routes with component.
<br></br>The application size is reduced by adding only the specific router module(Web, core, or native)</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

<p></p>

<p>Can you describe about componentDidCatch lifecycle method signature?</p>

A

<p></p>

<p>The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters,
<br></br>
<br></br>[1] error: - The error object which was thrown
<br></br>[2] info: - An object with a componentStack key contains the information about which component threw the error.
<br></br>The method structure would be as follows
<br></br>
<br></br>componentDidCatch(error, info)</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

<p></p>

<p>In which scenarios error boundaries do not catch errors?</p>

A

<p></p>

<p>Below are the cases in which error boundaries doesn't work,
<br></br>
<br></br>[1] Inside Event handlers
<br></br>[2] Asynchronous code using setTimeout or requestAnimationFrame callbacks
<br></br>[3] During Server side rendering
<br></br>[4] When errors thrown in the error boundary code itself</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

<p></p>

<p>Why do you not need error boundaries for event handlers?</p>

A

<p></p>

<p>Error boundaries do not catch errors inside event handlers.
<br></br>
<br></br>React doesn’t need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering. So if they throw, React still knows what to display on the screen.
<br></br>
<br></br>If you need to catch an error inside an event handler, use the regular JavaScript try / catch statement:
<br></br>
<br></br>class MyComponent extends React.Component {
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = { error: null };
<br></br> this.handleClick = this.handleClick.bind(this);
<br></br> }
<br></br>
<br></br> handleClick() {
<br></br> try {
<br></br> // Do something that could throw
<br></br> } catch (error) {
<br></br> this.setState({ error });
<br></br> }
<br></br> }
<br></br>
<br></br> render() {
<br></br> if (this.state.error) {
<br></br> return </p>

<h1>Caught an error.</h1>

<br></br> }
<br></br> return Click Me
<br></br> }
<br></br>}
<br></br>Note that the above example is demonstrating regular JavaScript behavior and doesn’t use error boundaries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

<p></p>

<p>What is the difference between try catch block and error boundaries?</p>

A

<p></p>

<p>Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.
<br></br>
<br></br>For example, the try catch block used for below imperative code
<br></br>
<br></br>try {
<br></br> showButton();
<br></br>} catch (error) {
<br></br> // ...
<br></br>}
<br></br>Whereas error boundaries wrap declarative code as below,
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

<p></p>

<p>What is the behavior of uncaught errors in react 16?</p>

A

<p></p>

<p>In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

<p></p>

<p>What is the proper placement for error boundaries?</p>

A

<p></p>

<p>The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,
<br></br>
<br></br>[1] You can wrap top-level route components to display a generic error message for the entire application.
<br></br>
<br></br>[2] You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

<p></p>

<p>What is the benefit of component stack trace from error boundary?</p>

A

<p></p>

<p>Apart from error messages and javascript stack, React16 will display the component stack trace with file names and line numbers using error boundary concept.
<br></br>
<br></br>For example, BuggyCounter component displays the component stack trace as below,</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

<p>What is the required method to be defined for a class component?</p>

A

<p>The render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

<p>What are the possible return types of render method?</p>

A

<p>Below are the list of following types used and return from render method,
<br></br>
<br></br>[1] React elements: Elements that instruct React to render a DOM node. It includes html elements such as </p>

<div></div>

and user defined elements.
<br></br>
<br></br>[2] Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements
<br></br>
<br></br>[3] Portals: Render children into a different DOM subtree.
<br></br>
<br></br>[4] String and numbers: Render both Strings and Numbers as text nodes in the DOM
<br></br>
<br></br>[5] Booleans or null: Doesn’t render anything but these types are used to conditionally render content.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

<p>What is the main purpose of constructor?</p>

A

<p>The constructor is mainly used for two purposes,
<br></br>
<br></br>[1] To initialize local state by assigning object to this.state
<br></br>[2] For binding event handler methods to the instance For example, the below code covers both the above cases,
<br></br>constructor(props) {
<br></br> super(props);
<br></br> // Don't call this.setState() here!
<br></br> this.state = { counter: 0 };
<br></br> this.handleClick = this.handleClick.bind(this);
<br></br>}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

<p>Is it mandatory to define constructor for React component?</p>

A

<p>No, it is not mandatory. i.e, If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.</p>

42
Q

<p>What are default props?</p>

A

<p>The defaultProps are defined as a property on the component class to set the default props for the class. This is used for undefined props, but not for null props.
<br></br>
<br></br>For example, let us create color default prop for the button component,
<br></br>
<br></br>class MyButton extends React.Component {
<br></br> // ...
<br></br>}
<br></br>
<br></br>MyButton.defaultProps = {
<br></br> color: 'red'
<br></br>};
<br></br>If props.color is not provided then it will set the default value to 'red'. i.e, Whenever you try to access the color prop it uses default value
<br></br>
<br></br>render() {
<br></br> return ; // props.color will be set to red
<br></br> }
<br></br>Note: If you provide null value then it remains null value.</p>

43
Q

<p>Why should not call setState in componentWillUnmount?</p>

A

<p>You should not call setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again.</p>

44
Q

<p>What is the purpose of getDerivedStateFromError?</p>

A

<p>This lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.
<br></br>
<br></br>The signature of the lifecycle method is as follows,
<br></br>
<br></br>static getDerivedStateFromError(error)
<br></br>Let us take error boundary use case with the above lifecycle method for demonstration purpose,
<br></br>
<br></br>class ErrorBoundary extends React.Component {
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = { hasError: false };
<br></br> }
<br></br>
<br></br> static getDerivedStateFromError(error) {
<br></br> // Update state so the next render will show the fallback UI.
<br></br> return { hasError: true };
<br></br> }
<br></br>
<br></br> render() {
<br></br> if (this.state.hasError) {
<br></br> // You can render any custom fallback UI
<br></br> return </p>

<h1>Something went wrong.</h1>

;
<br></br> }
<br></br>
<br></br> return this.props.children;
<br></br> }
<br></br>}

45
Q

<p>What is the methods order when component re-rendered?</p>

A

<p>An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered.
<br></br>
<br></br>static getDerivedStateFromProps()
<br></br>shouldComponentUpdate()
<br></br>render()
<br></br>getSnapshotBeforeUpdate()
<br></br>componentDidUpdate()</p>

46
Q

<p>What are the methods invoked during error handling?</p>

A

<p>Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
<br></br>
<br></br>[1] static getDerivedStateFromError()
<br></br>[2] componentDidCatch()</p>

47
Q

<p>What is the purpose of displayName class property?</p>

A

<p>The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.
<br></br>
<br></br>For example, To ease debugging, choose a display name that communicates that it’s the result of a withSubscription HOC.
<br></br>
<br></br>function withSubscription(WrappedComponent) {
<br></br> class WithSubscription extends React.Component {/* ... */}
<br></br> WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
<br></br> return WithSubscription;
<br></br>}
<br></br>function getDisplayName(WrappedComponent) {
<br></br> return WrappedComponent.displayName || WrappedComponent.name || 'Component';
<br></br>}</p>

48
Q

<p>What is the browser support for react applications?</p>

A

<p>React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn't support ES5 methods.</p>

49
Q

<p>What is the purpose of unmountComponentAtNode method?</p>

A

<p>This method is available from react-dom package and it removes a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns true if a component was unmounted and false if there was no component to unmount.
<br></br>
<br></br>The method signature would be as follows,
<br></br>
<br></br>ReactDOM.unmountComponentAtNode(container)</p>

50
Q

<p>What is code-splitting?</p>

A

<p>Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.
<br></br>
<br></br>For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. moduleA.js
<br></br>
<br></br>const moduleA = 'Hello';
<br></br>
<br></br>export { moduleA };
<br></br>App.js
<br></br>
<br></br>import React, { Component } from 'react';
<br></br>
<br></br>class App extends Component {
<br></br> handleClick = () => {
<br></br> import('./moduleA')
<br></br> .then(({ moduleA }) => {
<br></br> // Use moduleA
<br></br> })
<br></br> .catch(err => {
<br></br> // Handle failure
<br></br> });
<br></br> };
<br></br>
<br></br> render() {
<br></br> return (
<br></br> </p>

<div>
<br></br> Load
<br></br> </div>

<br></br> );
<br></br> }
<br></br>}
<br></br>
<br></br>export default App;

51
Q

<p>What is the benefit of strict mode?</p>

A

<p>The will be helpful in the below cases
<br></br>
<br></br>Identifying components with unsafe lifecycle methods.
<br></br>Warning about legacy string ref API usage.
<br></br>Detecting unexpected side effects.
<br></br>Detecting legacy context API.
<br></br>Warning about deprecated findDOMNode usage</p>

52
Q

<p>What are Keyed Fragments?</p>

A

<p>The Fragments declared with the explicit syntax may have keys. The general use case is mapping a collection to an array of fragments as below,
<br></br>
<br></br>function Glossary(props) {
<br></br> return (
<br></br> </p>

<dl>
<br></br> {props.items.map(item => (
<br></br> // Without the `key`, React will fire a key warning
<br></br>
<br></br> <dt>{item.term}</dt>
<br></br> <dd>{item.description}</dd>
<br></br>
<br></br> ))}
<br></br> </dl>

<br></br> );
<br></br>}
<br></br>Note: key is the only attribute that can be passed to Fragment. In the future, there might be a support for additional attributes, such as event handlers.

53
Q

<p>Does React support all HTML attributes?</p>

A

<p>As of React 16, both standard or custom DOM attributes are fully supported. Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs.
<br></br>
<br></br>Let us take few props with respect to standard HTML attributes,
<br></br>
<br></br></p>

<div></div>

  // Just like node.tabIndex DOM API <br><div></div> // Just like node.className DOM API <br>  // Just like node.readOnly DOM API <br>These props work similarly to the corresponding HTML attributes, with the exception of the special cases. It also support all SVG attributes.
54
Q

<p>What are the limitations with HOCs?</p>

A

<p>Higher-order components come with a few caveats apart from its benefits. Below are the few listed in an order,
<br></br>
<br></br>[1] Don’t use HOCs inside the render method: It is not recommended to apply a HOC to a component within the render method of a component.
<br></br>
<br></br>render() {
<br></br> // A new version of EnhancedComponent is created on every render
<br></br> // EnhancedComponent1 !== EnhancedComponent2
<br></br> const EnhancedComponent = enhance(MyComponent);
<br></br> // That causes the entire subtree to unmount/remount each time!
<br></br> return ;
<br></br>}
<br></br>The above code impacts on performance by remounting a component that causes the state of that component and all of its children to be lost. Instead, apply HOCs outside the component definition so that the resulting component is created only once.
<br></br>
<br></br>[2] Static methods must be copied over: When you apply a HOC to a component the new component does not have any of the static methods of the original component
<br></br>
<br></br>// Define a static method
<br></br>WrappedComponent.staticMethod = function() {/*...*/}
<br></br>// Now apply a HOC
<br></br>const EnhancedComponent = enhance(WrappedComponent);
<br></br>
<br></br>// The enhanced component has no static method
<br></br>typeof EnhancedComponent.staticMethod === 'undefined' // true
<br></br>You can overcome this by copying the methods onto the container before returning it,
<br></br>
<br></br>function enhance(WrappedComponent) {
<br></br> class Enhance extends React.Component {/*...*/}
<br></br> // Must know exactly which method(s) to copy :(
<br></br> Enhance.staticMethod = WrappedComponent.staticMethod;
<br></br> return Enhance;
<br></br>}
<br></br>
<br></br>[3] Refs aren’t passed through: For HOCs you need to pass through all props to the wrapped component but this does not work for refs. This is because ref is not really a prop similar to key. In this case you need to use the React.forwardRef API</p>

55
Q

<p>How to debug forwardRefs in DevTools?</p>

A

<p>React.forwardRef accepts a render function as parameter and DevTools uses this function to determine what to display for the ref forwarding component.
<br></br>
<br></br>For example, If you don't name the render function or not using displayName property then it will appear as ”ForwardRef” in the DevTools,
<br></br>
<br></br>const WrappedComponent = React.forwardRef((props, ref) => {
<br></br> return ;
<br></br>});
<br></br>But If you name the render function then it will appear as ”ForwardRef(myFunction)”
<br></br>
<br></br>const WrappedComponent = React.forwardRef(
<br></br> function myFunction(props, ref) {
<br></br> return ;
<br></br> }
<br></br>);
<br></br>As an alternative, You can also set displayName property for forwardRef function,
<br></br>
<br></br>function logProps(Component) {
<br></br> class LogProps extends React.Component {
<br></br> // ...
<br></br> }
<br></br>
<br></br> function forwardRef(props, ref) {
<br></br> return ;
<br></br> }
<br></br>
<br></br> // Give this component a more helpful display name in DevTools.
<br></br> // e.g. "ForwardRef(logProps(MyComponent))"
<br></br> const name = Component.displayName || Component.name;
<br></br> forwardRef.displayName = `logProps(${name})`;
<br></br>
<br></br> return React.forwardRef(forwardRef);
<br></br>}</p>

56
Q

<p>When component props defaults to true?</p>

A

<p>If you pass no value for a prop, it defaults to true. This behavior is available so that it matches the behavior of HTML.
<br></br>
<br></br>For example, below expressions are equivalent,
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>Note: It is not recommended to use this approach because it can be confused with the ES6 object shorthand (example, {name} which is short for {name: name})</p>

57
Q

<p>What is NextJS and major features of it?</p>

A

<p>Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS,
<br></br>
<br></br>Server-rendered by default
<br></br>Automatic code splitting for faster page loads
<br></br>Simple client-side routing (page based)
<br></br>Webpack-based dev environment which supports (HMR)
<br></br>Able to implement with Express or any other Node.js HTTP server
<br></br>Customizable with your own Babel and Webpack configurations</p>

58
Q

<p>How do you pass an event handler to a component?</p>

A

<p>You can pass event handlers and other functions as props to child components. It can be used in child component as below,</p>

59
Q

<p>Is it good to use arrow functions in render methods?</p>

A

<p>Yes, You can use. It is often the easiest way to pass parameters to callback functions. But you need to optimize the performance while using it.
<br></br>
<br></br>class Foo extends Component {
<br></br> handleClick() {
<br></br> console.log('Click happened');
<br></br> }
<br></br> render() {
<br></br> return this.handleClick()}>Click Me;
<br></br> }
<br></br>}
<br></br>
<br></br>Note: Using an arrow function in render method creates a new function each time the component renders, which may have performance implications</p>

60
Q

<p>How to prevent a function from being called multiple times?</p>

A

<p>If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,
<br></br>
<br></br>Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
<br></br>Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
<br></br>RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function</p>

61
Q

<p>How JSX prevents Injection Attacks?</p>

A

<p>React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.
<br></br>
<br></br>For example, you can embed user input as below,
<br></br>
<br></br>const name = response.potentiallyMaliciousInput;
<br></br>const element = </p>

<h1>{name}</h1>

;
<br></br>This way you can prevent XSS(Cross-site-scripting) attacks in the application.

62
Q

<p>How do you update rendered elements?</p>

A

<p>You can update UI(represented by rendered element) by passing the newly created element to ReactDOM's render method.
<br></br>
<br></br>For example, lets take a ticking clock example, where it updates the time by calling render method multiple times,
<br></br>
<br></br>function tick() {
<br></br> const element = (
<br></br> </p>

<div>
<br></br> <h1>Hello, world!</h1>
<br></br> <h2>It is {new Date().toLocaleTimeString()}.</h2>
<br></br> </div>

<br></br> );
<br></br> ReactDOM.render(element, document.getElementById(‘root’));
<br></br>}
<br></br>
<br></br>setInterval(tick, 1000);

63
Q

<p>How do you say that props are readonly?</p>

A

<p>When you declare a component as a function or a class, it must never modify its own props.
<br></br>
<br></br>Let us take a below capital function,
<br></br>
<br></br>function capital(amount, interest) {
<br></br> return amount + interest;
<br></br>}
<br></br>The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs. Hence, React has a single rule saying "All React components must act like pure functions with respect to their props."</p>

64
Q

<p>How do you say that state updates are merged?</p>

A

<p>When you call setState() in the component, React merges the object you provide into the current state.
<br></br>
<br></br>For example, let us take a facebook user with posts and comments details as state variables,
<br></br>
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = {
<br></br> posts: [],
<br></br> comments: []
<br></br> };
<br></br> }
<br></br>Now you can update them independently with separate setState() calls as below,
<br></br>
<br></br> componentDidMount() {
<br></br> fetchPosts().then(response => {
<br></br> this.setState({
<br></br> posts: response.posts
<br></br> });
<br></br> });
<br></br>
<br></br> fetchComments().then(response => {
<br></br> this.setState({
<br></br> comments: response.comments
<br></br> });
<br></br> });
<br></br> }
<br></br>As mentioned in the above code snippets, this.setState({comments}) updates only comments variable without modifying or replacing posts variable.</p>

65
Q

<p>How do you pass arguments to an event handler?</p>

A

<p>During iterations or loops, it is common to pass an extra parameter to an event handler. This can be achieved through arrow functions or bind method.
<br></br>
<br></br>Let us take an example of user details updated in a grid,
<br></br>
<br></br> this.updateUser(userId, e)}>Update User details
<br></br>Update User details
<br></br>
<br></br>In the both approaches, the synthetic argument e is passed as a second argument. You need to pass it explicitly for arrow functions and it will be passed automatically for bind method.</p>

66
Q

<p>How to prevent component from rendering?</p>

A

<p>You can prevent component from rendering by returning null based on specific condition. This way it can conditionally render component.
<br></br>
<br></br>function Greeting(props) {
<br></br> if (!props.loggedIn) {
<br></br> return null;
<br></br> }
<br></br>
<br></br> return (
<br></br> </p>

<div>
<br></br> welcome, {props.name}
<br></br> </div>

<br></br> );
<br></br>}
<br></br>
<br></br>
<br></br>class User extends React.Component {
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = {loggedIn: false, name: ‘John’};
<br></br> }
<br></br>
<br></br> render() {
<br></br> return (
<br></br> <div>
<br></br> //Prevent component render if it is not loggedIn
<br></br>
<br></br>
<br></br> </div>
<br></br> );
<br></br> }
<br></br>
<br></br>In the above example, the greeting component skips its rendering section by applying condition and returning null value.

67
Q

<p>What are the conditions to safely use the index as a key?</p>

A

<p>There are three conditions to make sure, it is safe use the index as a key.
<br></br>
<br></br>[1] The list and items are static– they are not computed and do not change
<br></br>[2] The items in the list have no ids
<br></br>[3] The list is never reordered or filtered.</p>

68
Q

<p>Should keys be globally unique?</p>

A

<p>The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.
<br></br>
<br></br>For example, the below Book component uses two arrays with different arrays,
<br></br>
<br></br>function Book(props) {
<br></br> const index = (
<br></br> </p>

<ul>
<br></br> {props.pages.map((page) =>
<br></br> <li>
<br></br> {page.title}
<br></br> </li>
<br></br> )}
<br></br> </ul>

<br></br> );
<br></br> const content = props.pages.map((page) =>
<br></br> <div>
<br></br> <h3>{page.title}</h3>
<br></br> <p>{page.content}</p>
<br></br> <p>{page.pageNumber}</p>
<br></br> </div>
<br></br> );
<br></br> return (
<br></br> <div>
<br></br> {index}
<br></br> <hr>
<br></br> {content}
<br></br> </div>
<br></br> );
<br></br>}

69
Q

<p>What is the popular choice for form handling?</p>

A

<p>Formik is a form library for react which provides solutions such as validation, keeping track of the visited fields, and handling form submission.
<br></br>
<br></br>In detail, You can categorize them as follows,
<br></br>
<br></br>[1] Getting values in and out of form state
<br></br>[2] Validation and error messages
<br></br>[3] Handling form submission
<br></br>
<br></br>It is used to create a scalable, performant, form helper with a minimal API to solve annoying stuff.</p>

70
Q

<p>What are the advantages of formik over redux form library?</p>

A

<p>Below are the main reasons to recommend formik over redux form library,
<br></br>
<br></br>[1] The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary.
<br></br>
<br></br>[2] Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE. This way it increases input latency for large apps.
<br></br>
<br></br>[3] Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB</p>

71
Q

<p>Why are you not required to use inheritance?</p>

A

<p>In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely. Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module. Later components import it and use that function, object, or class, without extending it.</p>

72
Q

<p>Can I use web components in react application?</p>

A

<p>Yes, you can use web components in a react application. Even though many developers won't use this combination, it may require especially if you are using third-party UI components that are written using Web Components.
<br></br>
<br></br>For example, let us use Vaadin date picker web component as below,
<br></br>
<br></br>import React, { Component } from 'react';
<br></br>import './App.css';
<br></br>import '@vaadin/vaadin-date-picker';
<br></br>class App extends Component {
<br></br> render() {
<br></br> return (
<br></br> </p>

<div>
<br></br>
<br></br> </div>

<br></br> );
<br></br> }
<br></br>}
<br></br>export default App;

73
Q

<p>What is dynamic import?</p>

A

<p>You can achieve code-splitting in your app using dynamic import.
<br></br>
<br></br>Let's take an example of addition,
<br></br>
<br></br>[1] Normal Import
<br></br>import { add } from './math';
<br></br>console.log(add(10, 20));
<br></br>
<br></br>[2] Dynamic Import
<br></br>import("./math").then(math => {
<br></br> console.log(math.add(10, 20));
<br></br>});</p>

74
Q

<p>What are loadable components?</p>

A

<p>If you want to do code-splitting in a server rendered app, it is recommend to use Loadable Components because React.lazy and Suspense is not yet available for server-side rendering. Loadable lets you render a dynamic import as a regular component.
<br></br>
<br></br>Lets take an example,
<br></br>
<br></br>import loadable from '@loadable/component'
<br></br>
<br></br>const OtherComponent = loadable(() => import('./OtherComponent'))
<br></br>
<br></br>function MyComponent() {
<br></br> return (
<br></br> </p>

<div>
<br></br>
<br></br> </div>

<br></br> )
<br></br>}
<br></br>Now OtherComponent will be loaded in a separated bundle

75
Q

<p>What is suspense component?</p>

A

<p>If the module containing the dynamic import is not yet loaded by the time parent component renders, you must show some fallback content while you’re waiting for it to load using a loading indicator. This can be done using Suspense component.
<br></br>
<br></br>For example, the below code uses suspense component,
<br></br>
<br></br>const OtherComponent = React.lazy(() => import('./OtherComponent'));
<br></br>
<br></br>function MyComponent() {
<br></br> return (
<br></br> </p>

<div>
<br></br> Loading...</div>

}>
<br></br>
<br></br>
<br></br>
<br></br> );
<br></br>}
<br></br>As mentioned in the above code, Suspense is wrapped above the lazy component.

76
Q

<p>What is route based code splitting?</p>

A

<p>One of the best place to do code splitting is with routes. The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time. Due to this, the user experience won't be disturbed.
<br></br>
<br></br>Let us take an example of route based website using libraries like React Router with React.lazy,
<br></br>
<br></br>import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
<br></br>import React, { Suspense, lazy } from 'react';
<br></br>
<br></br>const Home = lazy(() => import('./routes/Home'));
<br></br>const About = lazy(() => import('./routes/About'));
<br></br>
<br></br>const App = () => (
<br></br>
<br></br> Loading...}>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>);
<br></br>In the above code, the code splitting will happen at each route level.</p>

77
Q

<p>Give an example on How to use context?</p>

A

<p>Context is designed to share data that can be considered global for a tree of React components.
<br></br>
<br></br>For example, in the code below lets manually thread through a “theme” prop in order to style the Button component.
<br></br>
<br></br>//Lets create a context with a default theme value "luna"
<br></br>const ThemeContext = React.createContext('luna');
<br></br>// Create App component where it uses provider to pass theme value in the tree
<br></br>class App extends React.Component {
<br></br> render() {
<br></br> return (
<br></br>
<br></br>
<br></br>
<br></br> );
<br></br> }
<br></br>}
<br></br>// A middle component where you don't need to pass theme prop anymore
<br></br>function Toolbar(props) {
<br></br> return (
<br></br> </p>

<div>
<br></br>
<br></br> </div>

<br></br> );
<br></br>}
<br></br>// Lets read theme value in the button component to use
<br></br>class ThemedButton extends React.Component {
<br></br> static contextType = ThemeContext;
<br></br> render() {
<br></br> return ;
<br></br> }
<br></br>}

78
Q

<p>What is the purpose of default value in context?</p>

A

<p>The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.
<br></br>
<br></br>Below code snippet provides default theme value as Luna.
<br></br>
<br></br>const MyContext = React.createContext(defaultValue);</p>

79
Q

<p>How do you use contextType?</p>

A

<p>ContextType is used to consume the context object. The contextType property can be used in two ways,
<br></br>
<br></br>[1] contextType as property of class: The contextType property on a class can be assigned a Context object created by React.createContext(). After that, you can consume the nearest current value of that Context type using this.context in any of the lifecycle methods and render function.
<br></br>
<br></br>Lets assign contextType property on MyClass as below,
<br></br>
<br></br>class MyClass extends React.Component {
<br></br> componentDidMount() {
<br></br> let value = this.context;
<br></br> /* perform a side-effect at mount using the value of MyContext */
<br></br> }
<br></br> componentDidUpdate() {
<br></br> let value = this.context;
<br></br> /* ... */
<br></br> }
<br></br> componentWillUnmount() {
<br></br> let value = this.context;
<br></br> /* ... */
<br></br> }
<br></br> render() {
<br></br> let value = this.context;
<br></br> /* render something based on the value of MyContext */
<br></br> }
<br></br>}
<br></br>MyClass.contextType = MyContext;
<br></br>
<br></br>[2] Static field You can use a static class field to initialize your contextType using public class field syntax.
<br></br>
<br></br>class MyClass extends React.Component {
<br></br> static contextType = MyContext;
<br></br> render() {
<br></br> let value = this.context;
<br></br> /* render something based on the value */
<br></br> }
<br></br>}</p>

80
Q

<p>What is a consumer?</p>

A

<p>A Consumer is a React component that subscribes to context changes. It requires a function as a child which receives current context value as argument and returns a react node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.
<br></br>
<br></br>Lets take a simple example,
<br></br>
<br></br>
<br></br> {value => /* render something based on the context value */}</p>

81
Q

<p>How do you solve performance corner cases while using context?</p>

A

<p>The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders.
<br></br>
<br></br>For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for value.
<br></br>
<br></br>class App extends React.Component {
<br></br> render() {
<br></br> return (
<br></br>
<br></br>
<br></br>
<br></br> );
<br></br> }
<br></br>}
<br></br>This can be solved by lifting up the value to parent state,
<br></br>
<br></br>class App extends React.Component {
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = {
<br></br> value: {something: 'something'},
<br></br> };
<br></br> }
<br></br>
<br></br> render() {
<br></br> return (
<br></br>
<br></br>
<br></br>
<br></br> );
<br></br> }
<br></br>}</p>

82
Q

<p>What is the purpose of forward ref in HOCs?</p>

A

<p>Refs will not get passed through because ref is not a prop. It is handled differently by React just like key. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component. In this case, you can use Forward Ref API. For example, we can explicitly forward refs to the inner FancyButton component using the React.forwardRef API.
<br></br>
<br></br>The below HOC logs all props,
<br></br>
<br></br> function logProps(Component) {
<br></br> class LogProps extends React.Component {
<br></br> componentDidUpdate(prevProps) {
<br></br> console.log('old props:', prevProps);
<br></br> console.log('new props:', this.props);
<br></br> }
<br></br>
<br></br> render() {
<br></br> const {forwardedRef, ...rest} = this.props;
<br></br>
<br></br> // Assign the custom prop "forwardedRef" as a ref
<br></br> return ;
<br></br> }
<br></br> }
<br></br>
<br></br> return React.forwardRef((props, ref) => {
<br></br> return ;
<br></br> });
<br></br> }
<br></br>Let's use this HOC to log all props that get passed to our “fancy button” component,
<br></br>
<br></br> class FancyButton extends React.Component {
<br></br> focus() {
<br></br> // ...
<br></br> }
<br></br>
<br></br> // ...
<br></br> }
<br></br> export default logProps(FancyButton);
<br></br>Now let's create a ref and pass it to FancyButton component. In this case, you can set focus to button element.
<br></br>
<br></br> import FancyButton from './FancyButton';
<br></br>
<br></br> const ref = React.createRef();
<br></br> ref.current.focus();
<br></br> ;</p>

83
Q

<p>Is ref argument available for all functions or class components?</p>

A

<p>Regular function or class components don’t receive the ref argument, and ref is not available in props either. The second ref argument only exists when you define a component with React.forwardRef call.</p>

84
Q

<p>Why do you need additional care for component libraries while using forward refs?</p>

A

<p>When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library. This is because your library likely has a different behavior such as what refs get assigned to, and what types are exported. These changes can break apps and other libraries that depend on the old behavior.</p>

85
Q

<p>How to create react class components without ES6?</p>

A

<p>If you don’t use ES6 then you may need to use the create-react-class module instead. For default props, you need to define getDefaultProps() as a function on the passed object. Whereas for initial state, you have to provide a separate getInitialState method that returns the initial state.
<br></br>
<br></br>var Greeting = createReactClass({
<br></br> getDefaultProps: function() {
<br></br> return {
<br></br> name: 'Jhohn'
<br></br> };
<br></br> },
<br></br> getInitialState: function() {
<br></br> return {message: this.props.message};
<br></br> },
<br></br> handleClick: function() {
<br></br> console.log(this.state.message);
<br></br> },
<br></br> render: function() {
<br></br> return </p>

<h1>Hello, {this.props.name}</h1>

;
<br></br> }
<br></br>});
<br></br>
<br></br>Note: If you use createReactClass then auto binding is available for all methods. i.e, You don’t need to use .bind(this) with in constructor for event handlers.

86
Q

<p>Is it possible to use react without JSX?</p>

A

<p>Yes, JSX is not mandatory for using React. Actually it is convenient when you don’t want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children).
<br></br>
<br></br>For example, let us take a greeting example with JSX,
<br></br>
<br></br>class Greeting extends React.Component {
<br></br> render() {
<br></br> return </p>

<div>Hello {this.props.message}</div>

;
<br></br> }
<br></br>}
<br></br>
<br></br>ReactDOM.render(
<br></br> ,
<br></br> document.getElementById(‘root’)
<br></br>);
<br></br>
<br></br>You can write the same code without JSX as below,
<br></br>
<br></br>class Greeting extends React.Component {
<br></br> render() {
<br></br> return React.createElement(‘div’, null, Hello ${this.props.message});
<br></br> }
<br></br>}
<br></br>
<br></br>ReactDOM.render(
<br></br> React.createElement(Greeting, {message: ‘World’}, null),
<br></br> document.getElementById(‘root’)
<br></br>);

87
Q

<p>What is diffing algorithm?</p>

A

<p>React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.
<br></br>
<br></br>In this case, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:
<br></br>
<br></br>[1] Two elements of different types will produce different trees.
<br></br>[2] The developer can hint at which child elements may be stable across different renders with a key prop.</p>

88
Q

<p>What are the rules covered by diffing algorithm?</p>

A

<p>When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements. It covers the below rules during reconciliation algorithm,
<br></br>
<br></br>[1] Elements Of Different Types: Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. For example, elements to , or from to of different types lead a full rebuild.
<br></br>
<br></br>[2] DOM Elements Of The Same Type: When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. Lets take an example with same DOM elements except className attribute,
<br></br></p>

<div></div>

<br></br>
<br></br><div></div>
<br></br>
<br></br>[3] Component Elements Of The Same Type: When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls componentWillReceiveProps() and componentWillUpdate() on the underlying instance. After that, the render() method is called and the diff algorithm recurses on the previous result and the new result.
<br></br>
<br></br>[4] Recursing On Children: when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference. For example, when adding an element at the end of the children, converting between these two trees works well.
<br></br><ul>
<br></br> <li>first</li>
<br></br> <li>second</li>
<br></br></ul>
<br></br>
<br></br><ul>
<br></br> <li>first</li>
<br></br> <li>second</li>
<br></br> <li>third</li>
<br></br></ul>
<br></br>
<br></br>[5] Handling keys: React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a key can make the tree conversion efficient,
<br></br><ul>
<br></br> <li>Duke</li>
<br></br> <li>Villanova</li>
<br></br></ul>
<br></br>
<br></br><ul>
<br></br> <li>Connecticut</li>
<br></br> <li>Duke</li>
<br></br> <li>Villanova</li>
<br></br></ul>

89
Q

<p>When do you need to use refs?</p>

A

<p>There are few use cases to go for refs,
<br></br>
<br></br>Managing focus, text selection, or media playback.
<br></br>Triggering imperative animations.
<br></br>Integrating with third-party DOM libraries.</p>

90
Q

<p>Must prop be named as render for render props?</p>

A

<p>Even though the pattern named render props, you don’t have to use a prop named render to use this pattern. i.e, Any prop that is a function that a component uses to know what to render is technically a “render prop”. Lets take an example with the children prop for render props,
<br></br>
<br></br> (
<br></br> </p>

<p>The mouse position is {mouse.x}, {mouse.y}</p>

<br></br>)}/>
<br></br>Actually children prop doesn’t need to be named in the list of “attributes” in JSX element. Instead, you can keep it directly inside element,
<br></br>
<br></br>
<br></br> {mouse => (
<br></br> <p>The mouse position is {mouse.x}, {mouse.y}</p>
<br></br> )}
<br></br>
<br></br>While using this above technique(without any name), explicitly state that children should be a function in your propTypes.
<br></br>
<br></br>Mouse.propTypes = {
<br></br> children: PropTypes.func.isRequired
<br></br>};

91
Q

<p>What are the problems of using render props with pure components?</p>

A

<p>If you create a function inside a render method, it negates the purpose of pure component. Because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop. You can solve this issue by defining the render function as instance method.</p>

92
Q

<p>How do you create HOC using render props?</p>

A

<p>You can implement most higher-order components (HOC) using a regular component with a render prop. For example, if you would prefer to have a withMouse HOC instead of a component, you could easily create one using a regular with a render prop.
<br></br>
<br></br>function withMouse(Component) {
<br></br> return class extends React.Component {
<br></br> render() {
<br></br> return (
<br></br> (
<br></br>
<br></br> )}/>
<br></br> );
<br></br> }
<br></br> }
<br></br>}
<br></br>This way render props gives the flexibility of using either pattern.</p>

93
Q

<p>What is windowing technique?</p>

A

<p>Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtualized are popular windowing libraries which provides several reusable components for displaying lists, grids, and tabular data.</p>

94
Q

<p>How do you print falsy values in JSX?</p>

A

<p>The falsy values such as false, null, undefined, and true are valid children but they don't render anything. If you still want to display them then you need to convert it to string. Let's take an example on how to convert to a string,
<br></br>
<br></br></p>

<div>
<br></br> My JavaScript variable is {String(myVariable)}.
<br></br></div>

95
Q

<p>What is the typical use case of portals?</p>

A

<p>React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context (e.g. z-index, position, opacity) and you need to visually “break out” of its container.
<br></br>
<br></br>For example, dialogs, global message notifications, hovercards, and tooltips.</p>

96
Q

<p>How do you set default value for uncontrolled component?</p>

A

<p>In React, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you might want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.
<br></br>
<br></br>render() {
<br></br> return (
<br></br>
<br></br>
<br></br> User Name:
<br></br>
<br></br>
<br></br>
<br></br>
<br></br> );
<br></br>}
<br></br>The same applies for select and textArea inputs. But you need to use defaultChecked for checkbox and radio inputs.</p>

97
Q

<p>What is your favorite React stack?</p>

A

<p>Even though the tech stack varies from developer to developer, the most popular stack is used in react boilerplate project code. It mainly uses Redux and redux-saga for state management and asynchronous side-effects, react-router for routing purpose, styled-components for styling react components, axios for invoking REST api, and other supported stack such as webpack, reselect, ESNext, Babel. You can clone the project https://github.com/react-boilerplate/react-boilerplate and start working on any new react project.</p>

98
Q

<p>What is the difference between Real DOM and Virtual DOM?</p>

A

<p>Below are the main differences between Real DOM and Virtual DOM,</p>

99
Q

How to add Bootstrap to a react application?

A

Bootstrap can be added to your React app in a three possible ways,

[i] Using the Bootstrap CDN: This is the easiest way to add bootstrap. Add both bootstrap CSS and JS resources in a head tag.

[ii] Bootstrap as Dependency: If you are using a build tool or a module bundler such as Webpack, then this is the preferred option for adding Bootstrap to your React application
    npm install bootstrap

[iii] React Bootstrap Package: In this case, you can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components. Below packages are popular in this category,

(a) react-bootstrap
(b) reactstrap

100
Q

Can you list down top websites or applications using react as front end framework?

A

Below are the top 10 websites using React as their front-end framework,

Facebook
Uber
Instagram
WhatsApp
Khan Academy
Airbnb
Dropbox
Flipboard
Netflix
PayPal