All you need to know before going for a REACT.JS interview


BASIC STUFF :-
There are a couple primary pillars in the JavaScript toolchain: Dependency Management, Linting, Style-checking, Transpilation, and Compilation, Minification, Source-Mapping.

PROPS and STATE :-
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().
Every component's props object has a property named children.
this.props.children will return everything in between a component's opening and closing JSX tags.
There are two ways for a component to get dynamic information: props and state. Besides props and state, everything in a component should always stay exactly the same.
A component changes its state by calling the function this.setState
Any time that you call this.setState, this.setState AUTOMATICALLY calls render as soon as the state has changed.
Think of this.setState as actually being two things: this.setState, immediately followed by render.
That is why you can't call this.setState from inside of the render function!this.setState automatically calls render. If render calls this.setState, you will create an infinite loop
 a stateful component passes its state down to a stateless component.
A React component should use props to store information that can be changed, but can only be changed by a different component.
A React component should use state to store information that the component itself can change.
Stateless functional components usually have props passed to them :-
(JS function without render function )
propTypes are useful for two reasons.
1) The first reason is prop validation.
2) 2 is arguably more useful: documentation.


If you add .isRequired to a propType, then you will get a console warning if that prop isn't sent.
A controlled component, on the other hand, has no memory. If you ask it for information about itself, then it will have to get that information through props. Most React components are controlled.
In React, when you give an <input /> a value attribute, then something strange happens: the <input /> BECOMES controlled
Lifecycle methods are methods that get called at certain moments in a component's life.
You can write a lifecycle method that gets called right before a component renders for the first time.
You can write a lifecycle method that gets called right after a component renders, every time except for the first time.
You can attach lifecycle methods to a lot of different moments in a component's life. This has powerful implications!
There are three categories of lifecycle methods: mounting, updating, and unmounting.
A component "mounts" when it renders for the first time. This is when mounting lifecycle methods get called.
/* start of life cycle */
There are three mounting lifecycle methods:
componentWillMount
When a component renders for the first time, componentWillMount gets called right before render.
setTimeout(function(){
  ReactDOM.render(
    <Example />,
    document.getElementById('app')
  );
}, 2000);
componentWillMount does NOT get called, because mounting lifecycle events only execute the first time that a component renders.
render
render is a lifecycle method!
render belongs to two categories: mounting lifecycle methods, and updating lifecycle methods.
componentDidMount
When a component mounts, it automatically calls these three methods, in order.
There are five updating lifecycle methods:
componentWillReceiveProps
When a component instance updates, componentWillReceiveProps gets called before the rendering begins.
shouldComponentUpdate
If shouldComponentUpdate returns true, then nothing noticeable happens. But if shouldComponentUpdate returns false, then the component will not update! None of the remaining lifecycle methods for that updating period will be called, including render.
componentWillUpdate  componentWillUpdate gets called in between shouldComponentUpdate and render.
The main purpose of componentWillUpdate is to interact with things outside of the React architecture.
If you need to do non-React setup before a component renders, such as checking the window size or interacting with an API, then componentWillUpdate is a good place to do that
render
componentDidUpdateWhen a component instance updates, componentDidUpdate gets called after any rendered HTML has finished loading.
Whenever a component instance updates, it automatically calls all five of these

unmounting:-
componentWillUnmount
Here you can cancel any outgoing network requests, or remove all event listeners associated with the component.Basically, clean up anything to do that solely involves the component in question — when it’s gone, it should be completely gone.
Lifecycle pic :-
https://media.geeksforgeeks.org/wp-content/uploads/lifecycle_reactjs.jpg
/* End of lifecycle */


-----------------------------------------------------------------------------------------

General Interview questions

1. a) How React works? How Virtual-DOM works in React?

React creates a virtual DOM. When state changes in a component it firstly runs a “diffing” algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of diff.
The HTML DOM is always tree-structured — which is allowed by the structure of HTML document. The DOM trees are huge nowadays because of large apps. Since we are more and more pushed towards dynamic web apps (Single Page Applications — SPAs), we need to modify the DOM tree incessantly and a lot. And this is a real performance and development pain.
The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. It is not invented by React but it uses it and provides it for free. ReactElements lives in the virtual DOM. They make the basic nodes here. Once we defined the elements, ReactElements can be render into the "real" DOM.
Whenever a ReactComponent is changing the state, diff algorithm in React runs and identifies what has changed. And then it updates the DOM with the results of diff. The point is - it’s done faster than it would be in the regular DOM.

b) Differentiate between Real DOM and Virtual DOM.

Real DOM vs Virtual DOM


C) What is ReactDOM and what is the difference between ReactDOM and React?

Prior to v0.14, all ReactDOM functionality was part of React. But later, React and ReactDOM were split into two different libraries.
As the name implies, ReactDOM is the glue between React and the DOM. Often, we will only use it for one single thing: mounting with ReactDOM. Another useful feature of ReactDOM is ReactDOM.findDOMNode() which we can use to gain direct access to a DOM element.
For everything else, there’s React. We use React to define and create our elements, for lifecycle hooks, etc. i.e. the guts of a React application.


d) What is create-react-app?

create-react-app is the official CLI (Command Line Interface) for React to create React apps with no build configuration.
We don’t need to install or configure tools like Webpack or Babel. They are preconfigured and hidden so that we can focus on the code. We can install easily just like any other node modules. Then it is just one command to start the React project.

create-react-app my-app
It includes everything we need to build a React app:
·         React, JSX, ES6, and Flow syntax support.
·         Language extras beyond ES6 like the object spread operator.
·         Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
·         A fast interactive unit test runner with built-in support for coverage reporting.
·         A live development server that warns about common mistakes.
·         A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
2)  What are the major features of React? 
Major features of React are listed below:
  1. It uses the virtual DOM instead of the real DOM.
  2. It uses server-side rendering.
  3. It follows uni-directional data flow or data binding.
  4. Uses reusable/composable UI components to develop the view.
3)  List some of the major advantages of React.
Some of the major advantages of React are:
  1. It increases the application’s performance
  2. It can be conveniently used on the client as well as server side
  3. Because of JSX, code’s readability increases
  4. React is easy to integrate with other frameworks like Meteor, Angular, etc
  5. Using React, writing UI test cases become extremely easy
4) What are the limitations of React?
Limitations of React are listed below:
  1. React is just a library, not a full-blown framework
  2. Its library is very large and takes time to understand
  3. It can be little difficult for the novice programmers to understand
  4. Coding gets complex as it uses inline templating and JSX
5) Why can’t browsers read JSX?
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.

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
2
3
4
5
6
7
8
9
10
11
render(){
    return(       
          
<div>
             
<h1> Hello World from Edureka!!</h1>
         </div>
    );
}

7)  How is React different from Angular?

React vs Angular


React Components – React Interview Questions

8) 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.

1
2
3
4
5
6
7
8
9
10
11
12
//General way
render() {   
    return(
        <MyInput onChange={this.handleChange.bind(this) } />
    );
}
//With Arrow Function
render() { 
    return(
        <MyInput onChange={ (e) => this.handleOnChange(e) } />
    );
}
TOPICREACTANGULAR
1. ARCHITECTUREOnly the View of MVCComplete MVC
2. RENDERINGServer-side renderingClient-side rendering
3. DOMUses virtual DOMUses real DOM
4. DATA BINDINGOne-way data bindingTwo-way data binding
5. DEBUGGINGCompile time debuggingRuntime debugging
6. AUTHORFacebookGoogle
Real DOMVirtual  DOM
1. It updates slow.1. It updates faster.
2. Can directly update HTML.2. Can’t directly update HTML.
3. Creates a new DOM if element updates.3. Updates the JSX if element updates.
4. DOM manipulation is very expensive.4. DOM manipulation is very easy.
5. Too much of memory wastage.5. No memory wastage.
9) 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 libraries

10) How do you modularize code in React?
We can modularize code by using the export and import properties. They help in writing the components separately in different files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(          
<div>
              
<h1>This is a child component</h1>
           </div>
        );
    }
}
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {   
    render() {       
        return(          
             
<div>              
                <App />         
            </div>
      
        ); 
    }
}




11)  What can you do with HOC?
Higher Order Component is an advanced way of reusing the component logic.
HOC are ‘pure’ components.
HOC can be used for many tasks like:
  • Code reuse, logic and bootstrap abstraction
  • Render High jacking
  • State abstraction and manipulation
  • Props manipulation
12)  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.
React Redux – React Interview Questions

13) 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, a complicated model was created around models and views
14) Explain Flux.
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.flux -React Interview Questions - Edureka

15) 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.
16) What are the three principles that Redux follows?
  1. 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.
  2. 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. 
  3. 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.Store - React Interview Questions - Edureka

17)  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.

18) List down the components of Redux.

Redux is composed of the following components:
  1. Action – It’s an object that describes what happened.
  2. Reducer –  It is a place to determine how the state will change.
  3. Store – State/ Object tree of the entire application is saved in the Store.
  4. View – Simply displays the data provided by the Store.

19) Show how the data flows through Redux?

Data Flow in Redux - React Interview Questions - Edureka

20)  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 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.

21) How is Redux different from Flux?

Flux vs Redux

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

22) 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 – 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.
 React Router – React Interview Questions

23) 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.

24) 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.

25) 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>

26)  List down the advantages of React Router.

Few advantages are:
  1. 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>).
  2. No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the <BrowserRouter> component.
  3. 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.

27) How is React Router different from conventional routing?

Conventional Routing vs React Routing


MISC QUESTIONS:-

27) What is Redux Thunk used for?
Redux thunk is middleware that allows us to write action creators that return a function instead of an action. The thunk can then be used to delay the dispatch of an action if a certain condition is met. This allows us to handle the asyncronous dispatching of actions. The inner function receives the store methods dispatch and getState as parameters.
To enable Redux Thunk, we need to use applyMiddleware() as below
 import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API required redux@>=3.1.0
const store = createStore(
rootReducer,
appluMiddleware(thunk)
);

28) What is the difference between createElement and cloneElement?
createElement is the thing that JSX gets transpiled to and is the thing that React uses to make React Elements (protest representations of some UI). cloneElement is utilized as a part of request to clone a component and pass it new props. 
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
----------------------------------------------------------------------------------

References:-


https://blog.bitsrc.io/tagged/react
https://www.geeksforgeeks.org/reactjs-lifecycle-components/
https://jscomplete.com/learn/1rd-reactful#initializing

Interview questions links
https://www.edureka.co/blog/interview-questions/react-interview-questions/
https://github.com/sudheerj/reactjs-interview-questions
https://medium.com/@vigowebs/frequently-asked-react-js-interview-questions-and-answers-36f3dd99f486
https://www.toptal.com/react/interview-questions
https://hackr.io/blog/react-interview-questions
https://mindmajix.com/reactjs-interview-questions
https://www.codementor.io/blog/5-essential-reactjs-interview-questions-du1084ym1
https://devhints.io/react

Code samples

https://jasonwatmore.com/post/2017/09/16/react-redux-user-registration-and-login-tutorial-example
https://stackblitz.com/edit/react-redux-registration-login-example?file=index.js
https://github.com/redgoose-dev/react-photo-layout-editor





Comments

Post a Comment

Popular posts from this blog

Set up your VOIP based SIP soft phone and know more about VOIP

Front End Developer Interview quiestions- All in single blog

Data Science v/s Data engineer v/s Data Analyst