React Js Interview Questions
Find Latest React Js Interview Questions and Answers. react js interview questions tutorialspoint, reactjs interview questions pdf, react js interview questions edureka, reactjs interview questions, redux interview questions, redux interview questions and answers for experienced, react js tricky questions, react interview questions github, React.js interview questions 2017, React.js Interview Questions 2018
Best interview Questions 2018
- Home
- PHP
- PHP 7 interview questions
- Core php interview questions and answers
- Cakephp interview questions
- Codeiginator interview questions
- Phalcon interview questions
- Laravel interview questions
- Slim framework interview questions
- Zend Framework interview questions
- Yii 2 interview questions
- Symfony interview questions
- Silex framework interview questions
- PHP Nette Framework interview questions
- Fuel PHP interview questions
- PHPixie framework interview questions
- Best AJAX Interview Questions
Tuesday, May 8, 2018
Digital marketing Interview Questions - Online Interview Questions
Digital marketing Interview Questions - Online Interview Questions: Digital marketing Interview Questions: Digital Marketing is better than traditional marketing, can you plz explain the statement.Read latest interview questions and answers on Digital marketing.SEO is an acronym for Search engine optimization is basically one of the best strategies.
Saturday, April 21, 2018
20 Essential React.js Interview Questions 2017
Sharing 20 Essential React.js Interview Questions 2017
1. Explain the Virtual DOM, and a pragmatic overview of how React renders it to the DOM.
The Virtual DOM is an interesting concept; it’s a complex idea that boils down into a much simpler algorithm.
In React, if we create simple ES6 class and print it out, we have a function (as all functions can be used as a constructor in JavaScript):
Let’s inspect the output of
The Virtual DOM is not a simple
One thing to note is that the
In React, if we create simple ES6 class and print it out, we have a function (as all functions can be used as a constructor in JavaScript):
const app = () => {
let React = react,
{Component} = React,
DOM = reactDom
class Comments extends Component {
constructor(props){ super(props) }
render(){ return <div>test</div> }
}
console.log(Comments)
}
require('react', 'react-dom').then(app)
The console.log(Comments) gives us something that looks like this (after compiled by Babel from ES6 to ES5):function Comments(props) {
_classCallCheck(this, Comments);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Comments).call(this, props));
}
When we write something to draw a React Component to the screen, we might have something like the following:DOM.render(<Comments />, document.body)
The JSX gets transpiled into ES5 by Babel as well:DOM.render(React.createElement(Comments, null), document.body);
We can see that <Comments /> is transpiled directly into React.createElement(Comments, null). This is where we can see what a Virtual DOM object actually is: a plain JavaScript Object that represents the tag to be rendered onto the screen.Let’s inspect the output of
React.createElement():console.log(<div/>)
// or
console.log(React.createElement('div', null))
This gives us:{"type":"div","key":null,"ref":null,"props":{},"_owner":null,"_store":{}}
See how the type is a string? DOM.render({...}) gets this object above and looks at the type, and decides whether or not to reuse an existing <div> element on the DOM or create a new <div> and append it.The Virtual DOM is not a simple
Object – it is a recursive structure. For example, if we add two elements beneath the <div/>:console.log(<div><span/><button/></div>)
// or
console.log(React.createElement(
'div',
null,
React.createElement('span', null),
React.createElement('button', null)
))
What we get is a nested Object-tree:{
"type":"div",
"key":null,
"ref":null,
"props":{
"children": [
{"type":"span","key":null,"ref":null,"props":{}},
{"type":"button","key":null,"ref":null,"props":{}}
]
}
}
This is why, in a React Component’s code, we can access the child and ancestor elements via this.props.children. What React will do is walk down a very deep tree of nested Objects (depending on your UI complexity), each sitting in their parent element’s children.One thing to note is that the
type so far has just been a string. When a React Element is made from a custom Component (like Comments above), the type is a function:console.log(<Comments />)
// or
console.log(React.createElement(Comments, null))
gives us:{
"key":null,
"ref":null,
"props":{},
“type”: function Component() { ... }
}
You can play around with a web version of this code at Matthew Keas’ github.2. What is the significance of 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.
We have two
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.
Keys themselves should be a unique number or string; so if a React Component is the only child with its key, then React will repurpose the DOM Element represented by that key in future calls to
Let’s demonstrate this with a simple list of todos rendered with React:
It is worth noting here that if you render a homogenous array of children – such as the
Find More questions on React Js From https://www.onlineinterviewquestions.com/react-js-interview-questions/
Article Source: https://www.toptal.com/react/interview-questions
We have two
<TwitterUser> Components being rendered to a page, drawn in decreasing order of followers:-----------
| A - 103 |
-----------
-----------
| B - 92 |
-----------
Let’s say that B gets updated with 105 Twitter followers, so the app re-renders, and switches the ordering of A and B:-----------
| 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.
Keys themselves should be a unique number or string; so if a React Component is the only child with its key, then React will repurpose the DOM Element represented by that key in future calls to
render().Let’s demonstrate this with a simple list of todos rendered with React:
Interactive code sample available on Matthew Keas’ github.
class List extends Component {
constructor(p){
super(p)
this.state = {
items: Array(5).fill(1).map((x,i) => ({id:i}))
}
}
componentDidMount(){
const random = (a,b) => Math.random() < .5 ? -1 : 1
setInterval(() => {
this.setState({
items: this.state.items.sort(random)
})
}, 20)
}
render() {
let {items} = this.state
return <ul>
{items.map(item =>
<li key={item.id}>{item.id}</li>)}
</ul>
}
}
DOM.render(<List />, document.body)
The setInterval() occurring on mount reorders the items array in this.state every 20ms. Computationally, if React is reordering the items in state, then it would manipulate the DOM elements themselves instead of “dragging” them around between positions in the <ul>.It is worth noting here that if you render a homogenous array of children – such as the
<li>’s above – React will actually console.warn() you of the potential issue, giving you a stack trace and line number to debug from. You won’t have to worry about React quietly breaking.Find More questions on React Js From https://www.onlineinterviewquestions.com/react-js-interview-questions/
Article Source: https://www.toptal.com/react/interview-questions
Top 50 React Js Interview Questions 2018
Best React Js Interview Questions
Question: Explain React?
React is a front end JavaScript library developed by Facebook in 2011. It follows the component based approach which helps in building reusable UI components. It is used for developing complex and interactive web and mobile UI. Even though, it was open-sourced only in 2015, it has one of the largest communities supporting it.Question: List some features of React?
JSX: JSX is JavaScript syntax extension. Components : React is all about components. One direction flow: React implements one way data flow which makes it easy to reason about your appQuestion: List some of the major advantages of React.
Some of the major advantages of React are:- It increases the application's performance
- It can be used on client and server side
- Code's readability increases, because of JSX.
- It is easy to integrate with other frameworks such as Angular, Meteor etc
- Using React, writing UI test cases become extremely easy
- React uses virtual DOM which is JavaScript object.
- This will improve apps performance
- Component and Data patterns improve readability.
Question: What are the limitations of React?
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
Question: 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: render(){ return( <div> <h1> Welcome To Tekslate!!</h1> </div> ); }Question: Differentiate between Real DOM and Virtual DOM.
| Real DOM | Virtual DOM |
| It updates slowly. | It updates faster. |
| Can directly update HTML. | Can't directly update HTML. |
| Creates a new DOM if element updates. | Updates the JSX if element updates. |
| DOM manipulation is very expensive. | DOM manipulation is very easy. |
| Too much of memory wastage. | No memory wastage. |
Q. Real DOM vs Virtual DOM
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.Question: How is React different from Angular?
React vs Angular| TOPIC | REACT | ANGULAR |
| ARCHITECTURE | Only the View of MVC | Complete MVC |
| RENDERING | Server side rendering | Client side rendering |
| DOM | Uses virtual DOM | Uses real DOM |
| DATA BINDING | One-way data binding | Two-way data binding |
| DEBUGGING | Compile time debugging | Run time debugging |
| AUTHOR |
Question: Why can't browsers read JSX?
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.Question: Explain the purpose of render() in React.
Each React component must have a render() compulsory. If more than one HTML elements needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div> etc. It returns to the single react element which is the presentation of native DOM Component. This function must be kept pure i.e., it must return the same result each time it is invoked.Question: What is Props?
Props are short hand 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 through out 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.Question: What is a state in React and how is it used?
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().React JS Interview Questions And Answers
Question: Differentiate states and props.
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 |
Question: What is arrow function in React? How is it used?
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.//General way
render() { return( <MyInput onChange={this.handleChange.bind(this) } /> ); }//With Arrow Function
render() { return( <MyInput onChange={ (e) => this.handleOnChange(e) } /> ); }
Question: Differentiate between stateful and stateless components.
Stateful vs Stateless Components React| Stateful Component | Stateful Component |
| Stores info about component's state change in memory | Stores info about component's state change in memory |
| Have authority to change state | Do not have the authority to change state |
| Contains the knowledge of past, current and possible future changes in state | Contains no knowledge of past, current and possible future state changes |
| 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. |
Question: What are the different phases of React component's lifecycle?
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.Question: Explain the lifecycle methods of React components in detail.
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.Question: What is an event in React?
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.Question: 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.Question: List some of the cases when you should use Refs.
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 librariesQuestion: What do you know about controlled and uncontrolled components?
Controlled vs Uncontrolled Components| Controlled Components | Uncontrolled Components |
| They do not maintain their own state | They maintain their own state |
| Data is controlled by the parent component | Data is controlled by the DOM |
| They take in the current values through props and then notify the changes via callbacks. | Refs are used to get their current values |
Question: What are Higher Order Components(HOC)?
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 wraps 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.Question: What can you do with HOC?
HOC can be used for many tasks like:
- Code reuse, logic and bootstrap abstraction
- Render High jacking
- State abstraction and manipulation
- Props manipulation
Question: What are Pure 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.Question: What is the significance of keys in React?
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.Reactjs Interview Questions For Experienced
Question: What were the major problems with MVC framework?
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, complicated model was created around models and views
Question: What is Redux?
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.Question: What do you understand by “Single source of truth”?
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.Question: List down the components of Redux.
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.Question: How are Actions defined in Redux?
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: function addTodo(text) { return { type: ADD_TODO, text } }Question: 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.Question: What is the significance of Store in Redux?
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 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.Question: How is Redux different from Flux?
Flux vs Redux| Flux | Redux |
| The Store contains state and change logic | Store and change logic are separate |
| There are multiple stores | There is only one store |
| All the stores are disconnected and flat | Single store with hierarchical reducers |
| Has singleton dispatcher | No concept of dispatcher |
| React components subscribe to the store | Container components utilize connect |
| State is mutable | State is immutable |
Question: What are the advantages of Redux?
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
: It is simple to maintain with a strict structure and predictable outcome.Server side rendering
: To the client side, You just need to pass the store created on the server. This is helpful for initial render and provides a high quality 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.Question: What is React Router?
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.Question: Why is switch keyword used in React Router v4?
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.Question: Why do we need a Router in React?
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 2 3 4 5 | <switch> <route exact path='/' component={Home}/> <route path='/posts/:id' component={Newpost}/> <route path='/posts' component={Post}/> </switch> |
Question: List down the advantages of React Router.
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>). No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the<BrowserRouter> component. The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It's easy to switch over based on similar coding style.Question: How is React Router different from conventional routing?
| Topic | Conventional Routing | React Routing |
| PAGES INVOLVED | Each view corresponds to a new file | Only single HTML page is involved |
| URL CHANGES | A HTTP request is sent to server and corresponding HTML page is received | Only the History attribute is changed |
| FEEL | User actually navigates across different pages for each view | User is duped thinking he is navigating across different pages |
Subscribe to:
Comments (Atom)