interviewquestions
interviewquestions
com/sudheerj/reactjs-interview-
questions#when-to-use-a-class-component-over-a-
function-component
Edureka
6. What is JSX?
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. Below is an example of JSX:
1 render(){
2 return(
3
4 <div>
5
6 <h1> Hello World from Edureka!!</h1>
7
8 </div>
9
);
10 }
11
Instructor-led Sessions
Assessments
Assignments
Lifetime Access
Explore Curriculum
A virtual DOM is a lightweight JavaScript object which originally is just the copy of
the real DOM. It is a node tree that lists the elements, their attributes and content as
Objects and their properties. React’s render function creates a node tree out of the
React components. It then updates this tree in response to the mutations in the data
model which is caused by various actions done by the user or by the system.
This Virtual DOM works in three simple steps.
2. Then the difference between the previous DOM representation and the new
one is calculated.
3. Once the calculations are done, the real DOM will be updated with only the
Browsers can only read JavaScript objects but JSX in not a regular JavaScript
object. Thus to enable a browser to read JSX, first, we need to transform JSX file
into a JavaScript object using JSX transformers like Babel and then pass it to the
browser.
i. require vs import
1 // ES5
2 var React = require('react');
3
4 // ES6
import React from 'react';
5
1 // ES5
2 module.exports = Component;
3
4 // ES6
export default Component;
5
1
2 // ES5
3 var MyComponent = React.createClass({
4 render: function() {
5 return
6
<h3>Hello Edureka!</h3>
7 ;
8 }
9 });
10
11 // ES6
class MyComponent extends React.Component {
12
render() {
13 return
14
15 <h3>Hello Edureka!</h3>
16 ;
17 }
}
18
19
iv. props
1 // ES5
var App = React.createClass({
2
propTypes: { name: React.PropTypes.string },
3 render: function() {
4 return
5
6 <h3>Hello, {this.props.name}!</h3>
7 ;
}
8 });
9
10 // ES6
11
12 class App extends React.Component {
13 render() {
14 return
15
16 <h3>Hello, {this.props.name}!</h3>
17 ;
}
18 }
19
20
v. state
1
2
3 // ES5
4 var App = React.createClass({
getInitialState: function() {
5 return { name: 'world' };
6 },
7 render: function() {
8 return
9
<h3>Hello, {this.state.name}!</h3>
10 ;
11 }
12 });
13
14 // ES6
15 class App extends React.Component {
constructor() {
16 super();
17 this.state = { name: 'world' };
18 }
19 render() {
return
20
21
<h3>Hello, {this.state.name}!</h3>
22 ;
23 }
24 }
25
26
10. How is React different from Angular?
React vs Angular
TOPIC REACT ANGULAR
1. ARCHITECTURE Only the View of MVC Complete MVC
2. RENDERING Server-side rendering Client-side rendering
3. DOM Uses virtual DOM Uses real DOM
4. DATA BINDING One-way data binding Two-way data binding
5. DEBUGGING Compile time debugging Runtime debugging
6. AUTHOR Facebook Google
React Components – React Interview Questions
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.
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.
13. How can you embed two or more components into one?
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.
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 via this.state().
States vs Props
Conditions State Props
1. Receive initial value from parent component Yes Yes
2. Parent component can change value No Yes
3. Set default values inside component Yes Yes
4. Changes inside component Yes No
5. Set initial value for child components Yes Yes
6. Changes inside child components No Yes
17. How can you update the state of a component?
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 //General way
3 render() {
return(
4 <MyInput onChange={this.handleChange.bind(this) } />
5 );
6 }
7 //With Arrow Function
render() {
8
return(
9 <MyInput onChange={ (e) => this.handleOnChange(e) } />
10 );
11 }
12
19. Differentiate between stateful and stateless components.
Stateful vs Stateless
Stateful Component Stateless Component
1. Stores info about component’s state change 1. Calculates the internal state of the
in memory components
2. Have authority to change state 2. Do not have the authority to change state
3. Contains the knowledge of past, current and 3. Contains no knowledge of past, current
possible future changes in state and possible future state changes
4. Stateless components notify them about the 4. They receive the props from the Stateful
requirement of the state change, then they send components and treat them as callback
down the props to them. functions.
20. What are the different phases of React component’s lifecycle?
i. Initial Rendering Phase: This is the phase when the component is about to
start its life journey and make its way to the DOM.
ii. 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.
iii. Unmounting Phase: This is the final phase of a component’s life cycle in
which the component is destroyed and removed from the DOM.
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:
i. Events are named using camel case instead of just using the lowercase.
ii. 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.
23. How do you create an event in React?
1
2 class Display extends React.Component({
show(evt) {
3 // code
4 },
5 render() {
6 // Render the div with an onClick prop (value is a function)
7 return (
8
<div onClick={this.show}>Click Me!</div>
9
10 );
11 }
12 });
13
24. What are synthetic events in React?
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.
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.
Next
1 class ReferenceDemo extends React.Component{
display() {
2
const name = this.inputDemo.value;
3 document.getElementById('disp').innerHTML = name;
4 }
5 render() {
6 return(
7
<div>
8 Name: <input type="text" ref={input => this.inputDemo = input}
9 <button name="Click" onClick={this.display}>Click</button>
10
11 <h2>Hello <span id="disp"></span> !!!</h2>
12
13 </div>
14 );
}
15 }
16
17
18
26. List some of the cases when you should use Refs.
We can modularize code by using the export and import properties. They help in
writing the components separately in different files.
1
2
//ChildComponent.jsx
3 export default class ChildComponent extends React.Component {
4 render() {
5 return(
6
7 <div>
8
9 <h1>This is a child component</h1>
10
</div>
11
12 );
13 }
14 }
15
16 //ParentComponent.jsx
17 import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {
18 render() {
19 return(
20
21 <div>
22 <App />
23 </div>
24
);
25 }
26 }
27
28
28. How are forms created in React?
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.
1
2 handleSubmit(event) {
3 alert('A name was submitted: ' + this.state.value);
4 event.preventDefault();
}
5
6 render() {
7 return (
8
9 <form onSubmit={this.handleSubmit}>
10 <label>
11 Name:
<input type="text" value={this.state.value} onChange={this.h
12 </label>
13 <input type="submit" value="Submit" />
14 </form>
15
16 );
17 }
18
29. What do you know about controlled and uncontrolled
components?
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.
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.
arguments.
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.
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:
1 function addTodo(text) {
2 return {
3 type: ADD_TODO,
4 text
}
5
}
6
42. Explain the role of Reducer.
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.
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.
Flux vs Redux
Flux Redux
1. The Store contains state and change logic 1. Store and change logic are separate
2. There are multiple stores 2. There is only one store
3. All the stores are disconnected and flat 3. Single store with hierarchical reducers
4. Has singleton dispatcher 4. No concept of dispatcher
5. React components subscribe to the store 5. Container components utilize connect
6. State is mutable 6. State is immutable
45. What are the advantages of Redux?
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.
Although a <div> 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.
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.
1 <switch>
2 <route exact path=’/’ component={Home}/>
3 <route path=’/posts/:id’ component={Newpost}/>
4 <route path=’/posts’ component={Post}/>
</switch>
5
49. List down the advantages of React Router.
i. 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>).
ii. No need to manually set History value: In React Router v4, all we need to do
is wrap our routes within the <BrowserRouter> component.
iii. 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.
</div>
}
}
VIMP: Whar are the keys in React?
Keys in React are used to identify unique VDOM Elements with their
corresponding data driving the UI; having them helps React optimize
rendering by recycling existing DOM elements. Let’s look at an
example to portray this.
-----------
| B - 105 |
-----------
-----------
| A - 103 |
-----------
Without keys, React would primarily re-render
both <TwitterUser> Elements in the DOM. It would re-use DOM
elements, but React won’t re-order DOM Elements on the screen.
With keys, React would actually re-order the DOM elements, instead
of rendering a lot of nested DOM changes. This can serve as a huge
performance enhancement, especially if the DOM and VDOM/React
Elements being used are costly to render.