Skip to content

Looking forward to appear in React Interview, here are the key React Interview Questions with Answers only for you.

Notifications You must be signed in to change notification settings

aatul/ReactJS-and-Redux-Questions-Answers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 

Repository files navigation

ReactJS and Redux Questions Answers

Looking forward to appear in React and Redux Interview, here are the key React and Redux Interview Questions with Answers only for you.

Table of Contents

Sr.No. Question
1 How does React work? How does Virtual-DOM work in React?
2 What is JSX?
3 What is the difference between Element and Component?
4 What is React.createClass?
5 Describe the key differences in React & Angular? / Angular vs React?
6 What are Redux-Observables?
7 What is React DOM and what is the difference between React DOM and React?
8 What are the differences between a Class component and Functional component?
9 What is the difference between state and props?
10 What are Controlled components?
11 What is a Higher Order component?
12 What is create-react-app?
13 What is Redux?
14 What is Redux Thunk used for?
15 What is PureComponent? When to use PureComponent over Component?
16 How Virtual-DOM is more efficient than Dirty checking?
17 What is FLUX in ReactJs?
18 What are the refs in React?
19 What is the stable version of ReactJs?
20 Is setState() async? Why is setState() in React Async instead of Sync?
21 What is render() in React? And explain its purpose?
22 What are controlled and uncontrolled components in React?
23 Explain the components of Redux?
24 What is React.cloneElement? And the difference with this.props.children?
25 What is the second argument that can optionally be passed to setState and what is its purpose?
26 What is the difference between React Native and React?
27 Principal features/benefits of Redux?
28 Redux change of state?
29 Redux workflow features?
30 Explain actions in Redux?

1. How does React work? How does Virtual-DOM work 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 documents. 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/constantly 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 define the elements, ReactElements can be rendered 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.

The major features of React are:

  • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • Follows Unidirectional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

Back to Top


2. What is JSX?

JSX is a syntax extension to JavaScript and comes with the full power of JavaScript.

  • JSX produces React “elements”.
  • You can embed any JavaScript expression in JSX by wrapping it in curly braces.

After compilation, JSX expressions become regular JavaScript objects. This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions. Even Though React does not require JSX, it is the recommended way of describing our UI in React app.

For example, below is the syntax for a basic element in React with JSX and its equivalent without it.

const element=(
  <h1 classname="greeting">
    Hello World!
  </h1>

Equivalent of the above using React.createElement

const element= React.createElement(
  'h1',
  {"classname": "greeting"},
  'Hello World!'
);

Back to Top


3. What is the difference between Element and Component?

An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.

The object representation of React Element would be as follows:

const element = React.createElement(
  'div',
  {id: 'login-btn'},
  'Login'
)

The above React.createElement() function returns an object:

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

And finally it renders to the DOM using ReactDOM.render():

<div id='login-btn'>Login</div>

Whereas a component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:

const Button = ({ onLogin }) =>
  <div id={'login-btn'} onClick={onLogin}>Login</div>

Then JSX gets transpiled to a React.createElement() function tree:

const Button = ({ onLogin }) => React.createElement(
  'div',
  { id: 'login-btn', onClick: onLogin },
  'Login'
)

Back to Top


4. What is React.createClass?

React.createClass allows us to generate component "classes." But with ES6, React allows us to implement component classes that use ES6 JavaScript classes. The end result is the same -- we have a component class. But the style is different. And one is using a "custom" JavaScript class system (createClass) while the other is using a "native" JavaScript class system.

When using React’s createClass() method, we pass in an object as an argument. So we can write a component using createClass that looks like this:

import React from 'react';

const Contacts = React.createClass({
  render(){
    return(
      <div></div>
    )
  }
});

export default Contacts;

Using an ES6 class to write the same component is a little different. Instead of using a method from the react library, we extend an ES6 class that the library defines, Component.

import React from 'react';

const Contacts extends React.Component({
  constructor(props){
    super(props);
  }
  
  render(){
    return(
      <div></div>
    )
  }
});

export default Contacts;

constructor() is a special function in a JavaScript class. JavaScript invokes constructor() whenever an object is created via a class.

Back to Top


5. Describe the key differences in React & Angular? / Angular vs React?

React Js Angular Js
React is a JavaScript library for building user interfaces. Angular is a TypeScript-based, open-source front-end web application platform.
React uses a virtual DOM. Angular uses the browser's DOM
React, is a JavaScript library as well, but recommends using JSX. Angularis a JS framework by nature, but is built to use TypeScript.
React - Low Learning Curve Angular - High Learning Curve
React is just more of a 'V' in the MVC. Angular is a fully-featured MVC framework.
While React can be bundled with other programming libraries, Angular is a complete solution in itself. For unidirectional data flow, React needs to be augmented by Redux. Angular uses a two-directional data flow process where it updates the Real DOM directly while React updates only the Virtual DOM and is concerned with the one-directional data flow.
Dynamic Applications: React will be a great choice because it uses a virtual DOM. It can quickly incorporate and "react" to the data changes made in the view by the users. Single Page Apps: Angular will be a great solution because it can display all changes made to the content without reloading the current page.
React has a sibling by the name of React Native, which allows you to build a complete mobile app for either Android or iOS. Not a web app that runs on a mobile phone, but a full-fledged mobile app built with JavaScript. With Angular you can build hybrid mobile apps, but let's be fair, a native mobile app will always outdo a hybrid mobile app.

Back to Top


6. What are Redux-Observables?

Another popular solution for handling async operations is Redux-Observable. As the name already suggests Redux-Observable is built around the concept of observables and reactive streams.

It is basically just a thin middleware wrapper around RxJS with just a few additional helper methods. Therefore you also need to add RxJS to your application if you want to use Redux-Observable.

Similar to how sagas are handled, side effects in Redux-Observable are separated from other redux code and are handled in so-called epics. An epic is basically just a function which takes a stream of actions and returns a new stream of actions. Note though, that an action already has flown through your reducers at the time it arrives in your epics.

Back to Top


7. What is React DOM and what is the difference between React DOM 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.

Back to Top


8. What are the differences between a Class component and Functional component?

Class components allow us to use additional features such as local state and lifecycle hooks. Also, to enable our component to have direct access to our store and thus hold state.

When our component just receives props and renders them to the page, this is a ‘stateless component’, for which a pure function can be used. These are also called dumb components or presentational components.

From the previous question, we can say that our Booklist component is functional and is stateless.

// Booklist.js

import React from 'react';

const Booklist = books =>(
  <ul>
    {books.map(({title,author}) =>
      {title}-{author}
    )}
  </ul>
}

export default Contacts;

On the other hand, the BookListContainer component is a class component.

Back to Top


9. What is the difference between state and props?

The basic difference is: State is mutable and Pros are immutable.

The State is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

Props (short for properties) are a Component’s configuration. Props are how components talk to each other. They are received from above component and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data — callback functions may be passed in as props.

There is also the case that we can have default props so that props are set even if a parent component doesn’t pass props down.

class SearchBar extends Component{
  constructor(props){
    super(props);
    this.state = {term: '' };
  }
  
  render(){
    return(
      <div className="search-bar">
        <input 
          value={this.state.term}
          onChange={event => this.onInputChange(event.target.value)}/>
      </div>
    );
  }
  
  onInputChange(term){
    this.setState(term);
    this.props.onSearchTermChange(term);
  }
}

Props and State do similar things but are used in different ways. The majority of our components will probably be stateless. Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed. State is used for mutable data, or data that will change. This is particularly useful for user input.

Back to Top


10. What are Controlled components?

In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. When a user submits a form the values from the aforementioned elements are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in its state and will re-render the component each time the callback function e.g. onChange is fired as the state will be updated. A form element whose value is controlled by React in this way is called a "Controlled Component".

With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input.

Back to Top


11. What is a Higher Order component?

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API. They are a pattern that emerges from React’s compositional nature.

A higher-order component is a function that takes a component and returns a new component.

HOC’s allow you to reuse code, logic and bootstrap abstraction. HOCs are common in third-party React libraries. The most common is probably Redux’s connect function. Beyond simply sharing utility libraries and simple composition, HOCs are the best way to share behavior between React Components. If you find yourself writing a lot of code in different places that does the same thing, you may be able to refactor that code into a reusable HOC.

Back to Top


12. 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 it 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.
  • Auto prefixed 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 source maps.

Back to Top


13. What is Redux?

The basic idea of Redux is that the entire application state is kept in a single store. The store is simply a javascript object. The only way to change the state is by firing actions from your application and then writing reducers for these actions that modify the state. The entire state transition is kept inside reducers and should not have any side-effects.

Redux is based on the idea that there should be only a single source of truth for your application state, be it UI state like which tab is active or Data state like the user profile details.

{
  first_name: 'John',
  last_name: 'Doe',
  age: 28
}

All of these data is retained by redux in a closure that redux calls a store. It also provides us a recipe for creating the said store, namely createStore(x).

The createStore() function accepts another function, x as an argument. The passed in function is responsible for returning the state of the application at that point in time, which is then persisted in the store. This passed in function is known as the reducer. This is a valid example reducer function:

export default function reducer(state={}, action){
  return state;
}

This store can only be updated by dispatching an action. Our App dispatches an action, it is passed into reducer; the reducer returns a fresh instance of the state; the store notifies our App and it can begin its re-render as required.

Back to Top


14. 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 asynchronous 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 requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

Back to Top


15. What is PureComponent? When to use PureComponent over Component?

PureComponent is exactly the same as Component except that it handles the shouldComponentUpdate method for us. When props or state changes, PureComponent will do a shallow comparison on both props and state. Components on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

When comparing previous props and state to next, a shallow comparison will check that primitives have the same value (eg, 1 equals 1 or that true equals true) and that the references are the same between more complex javascript values like objects and arrays.

It is good to prefer PureComponent over Component whenever we never mutate our objects.

class MyComponent extends React.PureComponent{
  render(){
    return <div>Hello World!</div>
  }
}

Back to Top


16. How Virtual-DOM is more efficient than Dirty checking?

In React, each of our components have a state. This state is like an observable. Essentially, React knows when to re-render the scene because it is able to observe when this data changes. Dirty checking is slower than observables because we must poll the data at regular intervals and check all of the values in the data structure recursively. By comparison, setting a value on the state will signal to a listener that some state has changed, so React can simply listen for change events on the state and queue up re-rendering.

The virtual DOM is used for efficient re-rendering of the DOM. This isn’t really related to dirty checking your data. We could re-render using a virtual DOM with or without dirty checking. In fact, the diff algorithm is a dirty checker itself.

We aim to re-render the virtual tree only when the state changes. So, using an observable to check if the state has changed is an efficient way to prevent unnecessary re-renders, which would cause lots of unnecessary tree diffs. If nothing has changed, we do nothing.

Back to Top


17. What is FLUX in ReactJs?

Flux is an application architecture in React View Library which is designed by Facebook for creating data layers in an application based on JavaScript.

Back to Top


18. What are the refs in React?

For focus management, trigger animation we use refs in React. It also contains third party libraries.

Back to Top


19. What is the stable version of ReactJs?

Version: 15.5

Back to Top


20. Is setState() async? Why is setState() in React Async instead of Sync?

setState() actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus, the setState calls are asynchronous as well as batched for better UI experience and performance.

Back to Top


21. What is render() in React? And explain its purpose?

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.

Back to Top


22. What are controlled and uncontrolled components in React?

This relates to stateful DOM components (form elements) and the difference:

  • A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component “controls” it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a “dumb component”.
  • An Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

In most (or all) cases we should use controlled components.

Back to Top


23. Explain the components of Redux?

Redux is composed of the following components:

  • Action — Actions are payloads of information that send data from our application to our store. They are the only source of information for the store. We send them to the store using store.dispatch(). Primarily, they are just an object describing what happened in our app.
  • Reducer — Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes. So this place determines how the state will change to action.
  • Store — The Store is the object that brings Action and Reducer together. The store has the following responsibilities: Holds application state; Allows access to the state via getState(); Allows the state to be updated via dispatch(action); Registers listeners via subscribe(listener); Handles unregistering of listeners via the function returned by subscribe(listener).

It’s important to note that we’ll only have a single store in a Redux application. When we want to split your data handling logic, we’ll use reducer composition instead of many stores.

Back to Top


24. What is React.cloneElement? And the difference with this.props.children?

React.cloneElement clone and return a new React element using the passed element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

React.cloneElement only works if our child is a single React element. For almost everything {this.props.children} is the better solution. Cloning is useful in some more advanced scenarios, where a parent send in an element and the child component needs to change some props on that element or add things like ref for accessing the actual DOM element.

Back to Top


25. What is the second argument that can optionally be passed to setState and what is its purpose?

A callback function which will be invoked when setState has finished and the component is re-rendered.

Since the setState is asynchronous, which is why it takes in a second callback function. With this function, we can do what we want immediately after the state has been updated.

Back to Top


26. What is the difference between React Native and React?

React is a JavaScript library, supporting both front-end web and being run on the server, for building user interfaces and web applications.

On the other hand, React Native is a mobile framework that compiles to native app components, allowing us to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows us to use ReactJS to build our components and implement ReactJS under the hood.

With React Native it is possible to mimic the behavior of the native app in JavaScript and the end, we will get platform-specific code as the output. We may even mix the native code with JavaScript if we need to optimize our application further.

Back to Top


27. Principal features/benefits of Redux?

  • Maintainability: maintenance of Redux becomes easier due to strict code structure and organization.
  • Organization: code organization is very strict hence the stability of the code is high which intern increases the work to be much easier.
  • Server rendering: This is useful, particularly for the preliminary render, which keeps up a better user experience or search engine optimization. The server-side created stores are forwarded to the client-side.
  • Developer tools: It is Highly traceable so changes in position and changes in the application all such instances make the developers have a real-time experience.
  • Ease of testing: The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is made of functions that used to be: small, pure, and isolated.

Back to Top


28. Redux change of state?

For a release of action, a change in state to an application is applied, this ensures an intent to change the state will be achieved.

Example:

  • The user clicks a button in the application.
  • A function is called in the form of component.
  • So now an action gets dispatched by the relative container.
  • This happens because the prop (which was just called in the container) is tied to an action dispatcher using mapDispatchToProps (in the container).
  • Reducer on capturing the action it intern executes a function and this function returns a new state with specific changes.
  • The state change is known by the container and modifies a specific prop in the component as a result of the mapStateToProps function.

Back to Top


29. Redux workflow features?

Reset: Allow to reset the state of the store Revert: Roll back to the last committed state Sweep: All disabled actions that you might have fired by mistake will be removed Commit: makes the current state the initial state

Back to Top


30. Explain actions in Redux?

Actions in Redux are functions that return an action object. The action type and the action data are packed in the action object. which also allows a donor to be added to the system. Actions send data between the store and the application. All information retrieved by the store is produced by the actions.

export function addDonorAction(donor) {
  return {
    type: actionTypes.addDonor,
    donor,
  };
}

Internal Actions are built on top of Javascript objects and associate a type property to it.

Back to Top


Wish you all the luck