React Flashcards

1
Q

What is React?

A

React is a JavaScript library to facilitate the creation of interactive, stateful and reusable UI components.

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

What is the virtual DOM?

A

It is an abstraction of the HTML DOM. It allows React to do its computations within the abstract DOM without the real DOM operations, often slow and browser-specific.

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

In most cases, what do you need to to transform HTML code into a static React component?

A
  1. Return the HTML code in render.
  2. Replace class attribute name to className (because class is a reserved word in JavaScript).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the directory node_modules/?

A

It contains all the dependencies that the package manager loads based on the dependencies list defined in the package.json file.

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

What is the directory public/?

A
  • Public root of the site.
  • Files in there are accessible to anyone on the web.
  • Good place to keep static files and assets that are not being managed in the src/ directory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the src/ directory?

A

The application code!

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

Where does the browser look for the initial instructions to render the React app?

A

public/index.html

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

Does the public/index.html file has to be blank? Why not?

A

No: you can add whatever static design frame and elements around the React element, and know that the app will appear inside that element when JavaScript executes.

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

What is src/index.js?

A

It is the file where React looks for initial instructions to build UI inside the root element defined in public/index.html.

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

What are the two different ways to import modules, assuming Webpack is used?

A
  • Modules defined in package.json and installed can be imported by name ==> e.g. import {Module} from ‘module’;
  • Modules that are not package.json can still be imported by specifying a path to the file where those modules are defined ==> e.g. import {Module} from ‘path/to/module’;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the arguments of the render() function within src/index.js?

A
  1. A React component to render: the ‘App’ component from src/app.js
  2. A DOM node to serve as the render container, that is, the root element.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why can we use HTML and JSX expressions in a React app JavaScript file?

A

Because the JSX interpreter will compile the JSX tags and HTML tags into calls to React.createElement(). Incidently, the React module has to be imported even if not seemingly used.

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

What is the component < App/ >?

A
  • It is the first component the React app will call in index.js.
  • It serves as the container for rendering all the other components in the app.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are all components expected to do?

A

All components are expected to define a function called render() that returns some DOM elements.

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

Why are curly brackets special inside JSX tags?

A

They indicate that the code inside the curly brackets is JavaScript. It can be used to print the evaluated value of a JavaScript expression in the generated markup.

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

What cannot be put inside curly brackets inside JSX tags?

A

Statements CANNOT be within these curly brackets, but any JavaScript expression can be.

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

How to run a React app in development?

A

$ npm start

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

What does $ npm test does?

A

It launches a test runner (i.e. Jest) watching changes to the app and trying to run related tests.

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

What does $ npm run build does?

A

It packages the app for a production deployment, at /build/static/js/.

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

How does React handles non-JavaScript assets?

A

Webpack loaders (which create-react-app is using behind the scenes to build the app) let you load them directly in Javascript through the module system if files are included in the ‘src’ directory.

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

What is a SPA (Single Page Application)?

A

A SPA website usually loads once, then rewrites sections of a page rather than loading entire new pages from a server.

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

What are React components?

A
  • Conceptually, components are like JavaScript functions.
  • They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
  • Components are stateful and reusable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are Web components?

A
  • Reusable page elements that encapsulate pieces of functionality.
  • Examples:
    • Search input that offers live previews of search results.
    • Button that shows a tooltip on hover.
  • They are distinct and complementary to React components.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is JSX?

A
  • It is a templating language combining HTML and JavaScript into a single file.
  • It is mostly a syntactic convenience for building up JavaScript objects that describe DOM elements.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the rendering limitation of SPAs?

A
  • The client-side rendering that SPAs do means delayed rendering and delivering more JavaScript to the client.
  • This is a limitation that all JavaScript frameworks have.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the solution to the limitation of SPAs?

A

Frameworks such as React, Ember and Angular 2 are creating server-side rendering engines in Nodejs that can pre-render the app as static HTML, so that the browser has HTML to read immediately on page load.

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

What is the alternative to declaring a variable at the top of a file?

A

Make use of constructor function to declare the intitial state of a component:

import React from 'react';

class ComponentName extends React.Component { constructor(props) { super(props); this.state = { [var]: [expression] }; } render() { ... } }}

export default ComponentName;

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

What are props?

A

Props are arbitrary inputs accepted by components.

  • For components created as objects: props are a property of this.
  • For components created as functions, props are a function parameter.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How to pass an input as prop to a component?

A

Component some_prop=input / >

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

What care should be taken when accessing props within components?

A

Only access props (e.g. this.props) to read values. Never modify props inside components.

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

Components always need to have one top-level element. How to make sure they do?

A
  1. Add a single wrapper element: < div > … [your_elements] … < /div >
  2. Nest one of the top-level elements inside the other.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the basic structure of a Reat component?

A

import React from ‘react’;

class ComponentName extends React.Component {
 render() {
 return (
 [... some elements defined with JSX ...]
 );
 }
}
export default ComponentName;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the scope of state?

A

state is a private property of components. Only the corresponding component can read it and change it.

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

What is super(props)?

A

It is a JavaScript expression used to call functions on a parent’s object within a constructor function. It runs the constructor function of the parent component. props is passed along to make sure super() has access to the same arguments as the overwriting constructor.

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

How can a component share information about its state?

A

Pass the state explicitly via props in the call to an other component.

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

How to handle the different stages of component’s life in the DOM?

A
  • When a component’s output is first inserted into the DOM it will trigger a hook called componentDidMount().
  • When it’s removed from the DOM it will trigger one called componentWillUnmount().
  • These hooks are on the same level as render() and return(), and between them.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Where to store variables set within hooks?

A

They should be stored on the this object or on a variable initialized at the top of a file. Only variables used in render() should be stored in state.

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

How to trigger React to update?

A

Use the setState() method within a function inside a component:

class ComponentName extends React.Component {
 constructor(props) {
 super(props);
 this.state = {
 [var]: [expression]
 };
 }
 updateFunc() {
 this.setState({
 [var]: [expression]
 });
 }
 render() { ... 
 }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

how to refer to props or previous state when using setState?

A

Use a second form of setState that accepts a function as an argument, rather than directly passing the state (because value of state and prop may be unpredictable due to React asynchronous nature):

updateFunc() {

this.setState(function (prevState, props) {

return {

};

});

}

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

What is the basic structure to handle events in React?

A
class MyComponent extends React.Component {
 constructor(props) {
 super(props);
 this.handleClick = this.handleClick.bind(this);
 }
 handleClick(event) {
 console.log(this);
 }
 render() {
 return (
 [button onclick={this.handleClick}]
 Click me

[/button]
);
}
}

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

Why do we need to use a constructor to bind an event to this to handle events?

A

Because the value of this is not bound to the object where the function was originally defined. it is a common pattern when you define a class, and need to preserve reference to this inside its class functions after they are passed around to be executed as callbacks outside the orginal class context.

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

What does it mean that React has a unidirectional data flow?

A

Apps are organized as a series of nested components. These components are functional in nature: they receive information through the props attribute, and pass information via their return values. Data is passed down from components to their children.

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

Should components try to read or modify the DOM directly?

A

No, if you find yourself writing selectors to access elements on the page, then there is something wrong.

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

How can a child element trigger a change reflected in a parent component?

A

The parent component should pass one of its own functions as a callback in a prop when calling the child component.

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

What is the right place of an element of state if two or more components need to share access to it?

A

The right place of the element of state is in a common ancestor component.

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

What is the routing limitation of SPAs?

A

As the application is contained in a single page, it cannot rely on the browser’s forward/back buttons.

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

Add dependencies to package.json, either or both to production and development/test.

A
  • Production: $ npm install [package] –save
  • Development/test: $ npm install [package] –save-dev
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the role of React Router?

A

React Router fixes the routing limitation of PSAs. It allows the application to navigate between different components, changing the browser URL, modifying the browser history, and keeping the UI state in sync.

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

What are the components on which the React Router API is based?

A
  1. Router: keeps the UI in sync with the URL.
  2. Link: renders a navigation link to change the location.
  3. Route: renders a UI component depending on the URL.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What are the two router implementations and their URL formats?

A
  • BrowserRouter: using the HTML5 History API.
    • import { BrowserRouter } from ‘react-router-dom’;
    • http://localhost:3000/route/subroute
  • HashRouter: using the hash portion which sets or returns the anchor part of the URL.
    • import { HashRouter } from ‘react-router-dom’;​
    • http://localhost:3000/#/route/subroute
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

How many child elements a router component can have?

A

Only one child component.

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

What is the main job of the Router component?

A

The main job of a Router component is to create a history object to keep track of the location (URL). When the location changes because of a navigation action, the child component is re-rendered.

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

How to use the Link component?

A

[Link to=”route”] text [/Link]

54
Q

Where should the route components be defined?

A

The route components can be placed anywhere inside of the router, and the associated component will be rendered in that place, just like any other component.

55
Q

What is the different between using the Link component and directly using the [a href=”route”] element?

A

The Link components allow to change the URL without refreshing the page, which is not the case when using directly the [a] tag.

56
Q

What does it mean that routes are inclusive?

A

More than one [Route] component can match a URL path and render at the same time.

57
Q

What is the basic format of a route component? What does it do?

A
  • Format: [Route exact path=”/” component={MyComponent}]
  • The matching logic uses the path-to-regexp library: possibility to display different components just by declaring that they belong to the same (or similar) path.
58
Q

What is the use of the exact property for route components?

A

Renders the component only if the defined path matches the URL path exactly.

59
Q

What is the use of the [Switch] component?

A

Make the path matching exclusive rather than inclusive: it renders only the first route that matches the location.

60
Q

How to use the Switch components?

A

Insert Route components as child elements of the Switch component. Note that it is necessary to specify the exact property for the “/” path.

61
Q

How to handle a non-existent path?

A

Within a Switch component, use a [Redirect to=”path” /] component. This component will navigate to a new location overriding the current one in the history stack.

62
Q

What are the 3 properties passed as parameters when a component is rendered by the router?

A
  • match
  • location
  • history
63
Q

What are the properties of the match object created during a match between the router’s path and the URL location?

A
  • params: key/value pairs parsed from the URL.
  • isExact: true if the entire URL was matched.
  • path: path pattern used to match.
  • url: matched portion of the URL.
64
Q

How to define what is rendered by a Route component?

A

Use one of the 3 following properties:

  • component: render a component.
  • render: renders an element or component.
  • children: renders an element or component regardless of whether the path is matched or not.
65
Q

How to pass a prop to a component being rendered by React Router?

A
< Route 
    path="/some_path" 
    render={(props) => < Component {...props} myProp={myValue} / >}
/ >
66
Q

What is the ComponentWillMount life cycle method? What is its purpose?

A
  • Only called one time before the initial render().
  • Component does not have accees to the Natve UI (DOM, etc…) and children refs.
  • Opportunity to handle configuration, update our state and prepare for the first render().
  • Possible to safely query this.props and this.state knowing with certainty they are the current value.
67
Q

What is the best way to handle a Promise?

A
myPromise.then(function() {
   // Handle success
   // Some error may happen during handling of success
}).catch(function() {
   // Handle error
});
68
Q

What is Local Storage?

A

Local Storage is a Web API native to modern web browsers. It allows websites/apps to store simple and limited data in the browser, making that data available in future browser sessions.

69
Q

How to store and retrieve items from local storage?

A
// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
70
Q

How to use local storage as cache? Give an example of a search function with the native fetch API.

A
class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = { hits: null };
  }

  onSearch = (e) => {
    e.preventDefault();
    const { value } = this.input;

    if (value === '') {
      return;
    }
const cachedHits = localStorage.getItem(value);
if (cachedHits) {
  this.setState({ hits: JSON.parse(cachedHits) });
  return;
} ~~~

fetch('https://example.com/api/v1/search?query=' + value)
  .then(response => response.json())
  .then(result => this.onSetResult(result, value));   }

onSetResult = (result, key) => {
localStorage.setItem(key, JSON.stringify(result.hits));
this.setState({ hits: result.hits });
}
render() {…}
}
~~~

71
Q

What to use if you want the cache to be emptied when closing the browser?

A

Use sessionStorage instead of localStorage. Setter and getter are the same as localStorage.

72
Q

What is the purpose of withRouter?

A
  • When a component is rendered by React Router via component prop to a Route, that component is passed 3 different props: location, match and history.
  • If we render it ourselves (like < Component / > ), then we do not have access to these Router props. By adding the HOC withRouter in export default withRouter(Component), that takes care of this issue.
73
Q

What are the inputs of the WindowOrWorkerGlobalScope.fetch() method?

A
  • input: either a USVString containing a direct URL or a Request object.
  • init (optional): an object containing any custom settings that should be applied to the request, such as: method, headers, body…
74
Q

What is the return value of the WindowOrWorkerGlobalScope.fetch() method?

A

A Promise that resolves to a Response object.

75
Q

What are the properties of the Response object?

A
  • headers.
  • ok: boolean for success/failure.
  • redirected: boolean for whether or not the response’s URL list has more than one entry.
  • status: code.
  • statusText.
  • type: e.g. basic, cors.
  • url: final URL.
  • useFinalURL: boolean for whether this is the final URL of the response.
76
Q

What does Response.json() do?

A

The json() method of the Body class (inplemented by Response) takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

77
Q

What does Object.assign() do? Give its syntax.

A

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. The target object can be {}.

Syntax: const targetObject = Object.assign(target, …sources)

78
Q
A
79
Q

What does Promise.reject(reason) does?

A

It returns a Promise object that is rejected with the given reason. For debugging purposes and selective error catchng, it is useful to make reason an instance of Error.

80
Q

Give an example of Promise.reject().

A
Promise.reject(new Error('fail'))     
    .then(function() { 
        // not called 
    }, function(error) { 
        console.log(error); // Stacktrace 
    } 
);
81
Q

What is the flexbox algorithm?

A

An algorithm providing consistent layout on different screen sizes.

82
Q

What are the primary properties of flexboxes?

A
  • flexDirection.
  • alignItems.
  • justifyContent.
83
Q

What are the possible values of the flexDirection property of flexbox?

A

Determines the primary axis of a component’s layout: should the children be organized:

  • horizontally (row)
  • or vertically (column) ==> default.
84
Q

What are the possible values of the justifyContent property of flexbox?

A

Determines the distribution of children along the primary axis (X).

Positional alignments:

  • flex-start: aligns items at the beginning of the container ==> default.
  • center: aligns items at the center of the container.
  • flex-end: aligns items at the end of the container.

Distributed alignments:

  • space-around: evenly distributes items along the main axis such that all items have equal space around them.
  • space-between: evenly distributes items along the main axis such that the first item aligns at the start and the final item aligns at the end.
85
Q

What are the possible values of the alignItems property of flexbox?

A

Determines the alignment of children along the secondary axis (Y). If the primary axis is row, then the secondary is column, and vice versa.

Positional alignments:

  • flex-start: aligns items at the beginning of the container ==> default.
  • center: aligns items at the center of the container.
  • flex-end: aligns items at the end of the container.

Distributed alignments:

  • stretch: stretches the items to fill the container ==> default.
  • baseline: aligns the items so that their baselines align.
86
Q

How does a tradiotional website loads assets like CSS, images and web fonts?

A

A traditional website loads assets like CSS, images and web fonts from remote files based on urls in src attributes in HTML tags or stylesheet rules.

87
Q

Differentiate between Real DOM and Virtual DOM

A

Virtual DOM:

1) faster
2) can’t update html directly
3) updates the JSX if element updates (not creates a new DOM if element updates)
4) DOM manipulation is cheaper and easier
5) No memory wastage

88
Q

What are the major features of React?

A

It uses the virtual DOM instead of the real DOM.

It uses server-side rendering.

It follows uni-directional data flow or data binding.

89
Q

List some of the major advantages of React

A

Some of the major advantages of React are:

It increases the application’s performance

It can be conveniently used on the client as well as server side

Because of JSX, code’s readability increases

React is easy to integrate with other frameworks like Meteor, Angular, etc

Using React, writing UI test cases become extremely easy

90
Q

What are the limitations of React?

A

Limitations of React are listed below:

React is just a library, not a full-blown framework

Its library is very large and takes time to understand

It can be little difficult for the novice programmers to understand

Coding gets complex as it uses inline templating and JSX

91
Q

What is JSX?

A

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance.

92
Q

How different is React’s ES6 syntax when compared to ES5?

A

require vs import

export vs exports

component and function

props

state

https://www.edureka.co/blog/interview-questions/react-interview-questions/

93
Q

What do you understand from “In React, everything is a component.”

A

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

94
Q

Explain the purpose of render() in React.

A

Each React component must have a render() mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as

<form>, <group>,<div> etc. This function must be kept pure i.e., it must return the same result each time it is invoked.
</div></group>
</form>

95
Q

What is Props?

A

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

96
Q

What is a state in React and how is it used?

A

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed viathis.state().

97
Q

Differentiate between states and props.

A

States vs Props
ConditionsStateProps1. Receive initial value from parent componentYesYes2. Parent component can change valueNoYes3. Set default values inside componentYesYes4. Changes inside componentYesNo5. Set initial value for child componentsYesYes6. Changes inside child componentsNoYes

98
Q

How can you update the state of a component?

A

class MyComponent extends React.Component {

` ``constructor() {`

` super();`

` this.state = {`

` name:‘Maxx’``,`

` id:‘101’`

` ``}`

` ``}`

` ``render()`

` ``{`

` setTimeout(()=>{this.setState({name:‘Jaeha’, id:‘222’})},2000``)`

` ``return ( `

` `

` `

` `

Hello {this.state.name}

` `

` `

Your Id is {this.state.id}

` `

` ``);`

` ``}`

` ``}`

ReactDOM.render(

` , document.getElementById(‘content’``)`

);

99
Q

What is arrow function in React? How is it used?

A

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

1

2

3

4

5

6

7

8

9

10

11

12

//General way

render() {

` return(`

` ``this.handleChange.bind(this) } />`

` ``);`

}

//With Arrow Function

render() {

` return(`

` this``.handleOnChange(e) } />`

` ``);`

}

100
Q

Differentiate between stateful and stateless components.

A

Stateful vs Stateless

Stateful Component/ Stateless Component

  1. Stores info about component’s state change in memory
    / Calculates the internal state of the components
  2. Have authority to change state
    / Do not have the authority to change state
  3. Contains the knowledge of past, current and possible future changes in state
    / Contains no knowledge of past, current and possible future state changes
  4. Stateless components notify them about the requirement of the state change, then they send down the props to them.
    /They receive the props from the Stateful components and treat them as callback functions.
101
Q

What are the different phases of React component’s lifecycle?

A

There are three different phases of React component’s lifecycle:

Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.

Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.

Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.

102
Q

Explain the lifecycle methods of React components in detail.

A

Some of the most important lifecycle methods are:

componentWillMount() – Executed just before rendering takes place both on the client as well as server-side.

componentDidMount() – Executed on the client side only after the first render.

componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.

shouldComponentUpdate() – Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.

componentWillUpdate() – Called just before rendering takes place in the DOM.

componentDidUpdate() – Called immediately after rendering takes place.

componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

103
Q

What is an event in React?

A

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:

Events are named using camel case instead of just using the lowercase.

Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

104
Q

How do you create an event in React?

A
class Display extends React.Component({ 
show(evt) {
 // code 
 }, 
 render() { 
 // Render the div with an onClick prop (value is a function) 
 return ( 

Click Me!

);
}
});

105
Q

What are synthetic events in React?

A

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

106
Q

What do you understand by refs in React?

A

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

107
Q

List some of the cases when you should use Refs.

A

Following are the cases when refs should be used:

When you need to manage focus, select text or media playback

To trigger imperative animations

Integrate with third-party DOM libraries

108
Q

How do you modularize code in React?

A

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

109
Q

How are forms created in React?

A

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

110
Q

What do you know about controlled and uncontrolled components?

A

Controlled ComponentsUncontrolled Components

  1. They do not maintain their own state1. They maintain their own state
  2. Data is controlled by the parent component2. Data is controlled by the DOM
  3. They take in the current values through props and then notify the changes via callbacks3. Refs are used to get their current values
111
Q

What are Higher Order Components(HOC)?

A

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

112
Q

What can you do with HOC?

A

HOC can be used for many tasks like:

Code reuse, logic and bootstrap abstraction

Render High jacking

State abstraction and manipulation

Props manipulation

113
Q

What are Pure Components?

A

Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render(). These components enhance the simplicity of the code and performance of the application.

114
Q

What is the significance of keys in React?

A

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

115
Q

What were the major problems with MVC framework?

A

Following are some of the major problems with MVC framework:

DOM manipulation was very expensive

Applications were slow and inefficient

There was huge memory wastage

Because of circular dependencies, a complicated model was created around models and views

116
Q

Explain Flux.

A

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

117
Q

What is Redux?

A

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

118
Q

What are the three principles that Redux follows?

A

Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data.

Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.

119
Q

What do you understand by “Single source of truth”?

A

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

120
Q

List down the components of Redux.

A

Redux is composed of the following components:

Action – It’s an object that describes what happened.

Reducer – It is a place to determine how the state will change.

Store – State/ Object tree of the entire application is saved in the Store.

View – Simply displays the data provided by the Store.

121
Q

How are Actions defined in Redux?

A

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

122
Q

Explain the role of Reducer.

A

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

123
Q

What is the significance of Store in Redux?

A

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

124
Q

How is Redux different from Flux?

A

FluxRedux

  1. The Store contains state and change logic1. Store and change logic are separate
  2. There are multiple stores2. There is only one store
  3. All the stores are disconnected and flat3. Single store with hierarchical reducers
  4. Has singleton dispatcher4. No concept of dispatcher
  5. React components subscribe to the store5. Container components utilize connect
  6. State is mutable6. State is immutable
125
Q

What are the advantages of Redux?

A

Advantages of Redux are listed below:

Predictability of outcome – Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.

Maintainability – The code becomes easier to maintain with a predictable outcome and strict structure.

Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.

Developer tools – From actions to state changes, developers can track everything going on in the application in real time.

Community and ecosystem – Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.

Ease of testing – Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.

Organization – Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.

126
Q

What is React Router?

A

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

127
Q

Why is switch keyword used in React Router v4?

A

Although a

is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch> tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.
</switch>

128
Q

Why do we need a Router in React?

A

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.

129
Q

List down the advantages of React Router.

A

Few advantages are:

Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component (<browserrouter>) in which we enclose the specific child routes (<route>).</route></browserrouter>

No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the <browserrouter> component.</browserrouter>

The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.

130
Q

How is React Router different from conventional routing?

A

Conventional Routing vs React Routing

TopicConventional RoutingReact Routing

PAGES INVOLVEDEach view corresponds to a new fileOnly single HTML page is involved

URL CHANGESA HTTP request is sent to a server and corresponding HTML page is receivedOnly the History attribute is changed

FEELUser actually navigates across different pages for each viewUser is duped thinking he is navigating across different pages

131
Q
A