Google News
logo
ReactJS Interview Questions
React is an open-source frontend JavaScript library developed by Facebook in 2011. React was created by Jordan Walke, a software engineer working for Facebook.
 
* React is used for building user interfaces especially for single page applications.
 
* 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.
The major features of React are:
 
* It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
* It uses server-side rendering.
* It follows uni-directional data flow or data binding.
 
Uses reusable/composable UI components to develop the view.
JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.
 
In the example below text inside <h1> tag is returned as JavaScript function to the render function.
class App extends React.Component {
  render() {
    return(
      <div>
        <h1>{'Welcome to React world!'}</h1>
      </div>
    )
  }
}
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
There are two possible ways to create a component.
 
Function Components : This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as first parameter and return React elements:
function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>

}
Class Components : You can also use ES6 class to define a component. The above function component can be written as:
class Greeting extends React.Component {
  render() {
    return <h1>{`Hello, ${this.props.message}`}</h1>
  }
}
If the component needs state or lifecycle methods then use class component otherwise use function component. However, from React 16.8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component.
React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component 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.
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.
 
Let's create an user component with message state,
class User extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      message: 'Welcome to React world'
    }
  }

  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    )
  }
}
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.
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.
Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.
 
The primary purpose of props in React is to provide following component functionality:
 
* Pass custom data to your component.
* Trigger state changes.
* Use via this.props.reactProp inside component's render() method.

For example, let us create an element with reactProp property:
 
<Element reactProp={'1'} />

This reactProp (or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.
 
props.reactProp
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
The callback function is invoked when setState finished and the component gets rendered. Since setState() is asynchronous the callback function is used for any post action.
 
Note: It is recommended to use lifecycle method rather than this callback function.
 
setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))
The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.
componentWillMount : Executed before rendering and is used for App level configuration in your root component.
componentDidMount : Executed after first rendering and here all AJAX requests, DOM or state updates, and set up eventListeners should occur.
componentWillReceiveProps : Executed when particular prop updates to trigger state transitions.
shouldComponentUpdate : Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a rerender if component receives new prop.
componentWillUpdate : Executed before re-rendering the component when there are pros & state changes confirmed by shouldComponentUpdate which returns true.
componentDidUpdate : Mostly it is used to update the DOM in response to prop or state changes.
componentWillUnmount : It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.
It is one of the most in-demand libraries for front-end development in today’s growing world. It is defined as the predictable state container mainly designed for JavaScript apps and also it is used for managing the entire state of an application. Redux is very small in size and has no dependencies. It builds applications that are easy to deploy in different environments and easy to test. Redux is very small in size and has no dependencies.
Redux thunk acts as middleware which allows an individual to write action creators that return functions instead of actions. This is also used as a delay function in order to delay dispatch of an action if a certain condition is met. The two store methods getState() and dispatch() are provided as parameters to the inner function.
 
In order to activate Redux thunk, we must first use applyMiddleware() method as shown 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)
);
Basically, Flux is a basic illustration that is helpful in maintaining the unidirectional data stream.  It is meant to control construed data unique fragments to make them interface with that data without creating issues. Flux configuration is insipid; it's not specific to React applications, nor is it required to collect a React application.  Flux is basically a straightforward idea, however in you have to exhibit a profound comprehension of its usage.
React implements Synthetic events to improve the consistency and performance of applications and interfaces. The synthetic event is a cross-browser wrapper around the browser’s native event. It combines the behaviour of multiple browsers into a single API to make sure events have the same properties across different browsers and platforms.
React employs forms to enable users to interact with web applications.
 
Using forms, users can interact with the application and enter the required information whenever needed. Form contain certain elements, such as text fields, buttons, checkboxes, radio buttons, etc,.

Forms are used for many different tasks such as user authentication, searching, filtering, indexing, etc,.
A Higher-Order Component (HOC) is a function that takes a component and returns a new component, simple and enables re-usability. They are generally used when multiple components have to use a common logic. 
 
We call them pure components because they can accept any dynamically provided child component but they won't modify or copy any behavior from their input components.
 
const EnhancedComponent = higherOrderComponent(WrappedComponent)

HOC can be used for many use cases:
 
* Code reuse, logic and bootstrap abstraction.
* Render hijacking.
* State abstraction and manipulation.
* Props manipulation.
React Router is a routing library built on top of React, which is used to create routes in a React application. 
It maintains consistent structure and behavior and is used to develop single-page web applications. 
Enables multiple views in a single application by defining multiple routes in the React application.
Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.
The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.
JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.
You can add/edit props passed to the component using props proxy pattern like this:
function HOC(WrappedComponent) {
  return class Test extends Component {
    render() {
      const newProps = {
        title: 'New Header',
        footer: false,
        showFeatureX: false,
        showFeatureY: true
      }

      return <WrappedComponent {...this.props} {...newProps} />
    }
  }
}
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
 
For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.
 
const {Provider, Consumer} = React.createContext(defaultValue)
When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.
class is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the principal reason why React uses className instead of class. Pass a string as the className prop.
render() {
  return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
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
* 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
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    
    }
}
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.
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.
Ordinarily, you'd utilize Webpack's DefinePlugin strategy to set NODE_ENV to production. This will strip out things like prototype approval and additional notices. Over that, it's likewise a smart thought to minify your code in light of the fact that React utilizes Uglify's dead-code end to strip out advancement just code and remarks, which will radically diminish the measure of your package.
The server needs to be monitored to for updates with respect to time. The primary aim in most of the cases is to check whether novel comments are there or not. This process is basically considered as pooling. It checks for updates approximately every 5 seconds. It is possible to change this time period easily. Pooling help keeping an eye on the users and always make sure that no negative information is present on the servers. Actually, it can create issues related to several things and thus pooling is considered.
For all the available DOM objects in ReactJS, there is a parallel virtual DOM object. It is nothing but can be considered as the lighter version of the true copy and is powerful in eliminating the complex code. It is also used as a Blue Print for performing several basic experiments. Many developers also use it while practicing this technology.
MVC approaches are presently considered as outdated. Although they are capable to handle data concerns, controllers as well as UI, many developers found that it doesn’t properly work when applications size increases. However, they are capable to handle some of the key issues such as eliminating the lack of data integrity as well as managing the data flow which is not properly defined. On the other side, Flux works perfectly with all the sizes irrespective of their size.
React v15 provided very basic support for error boundaries using unstable_handleError method. It has been renamed to componentDidCatch in React v16.
Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.
The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
 
* render()
* hydrate()
* unmountComponentAtNode()
* findDOMNode()
* createPortal()
This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.
ReactDOM.render(element, container[, callback])
If the optional callback is provided, it will be executed after the component is rendered or updated.
The dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.
 
In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:
function createMarkup() {
  return { __html: 'First &middot; Second' }
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />
}
It is recommended to avoid async initialization in componentWillMount() lifecycle method. componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. We need to make sure async calls for component initialization happened in componentDidMount() instead of componentWillMount().
componentDidMount() {
  axios.get(`api/todos`)
    .then((result) => {
      this.setState({
        messages: [...result.data]
      })
    })
}
There are memoize libraries available which can be used on function components.
 
For example moize library can memoize the component in another component.
import moize from 'moize'
import Component from './components/Component' // this module exports a non-memoized component

const MemoizedFoo = moize.react(Component)

const Consumer = () => {
  <div>
    {'I will memoize the following entry:'}
    <MemoizedFoo/>
  </div>
}
Update : Since React v16.6.0, we have a React.memo. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.
  const MemoComponent = React.memo(function MemoComponent(props) {
    /* render using props */
  });
  OR
  export default React.memo(MyFunctionComponent);
React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.
import ReactDOMServer from 'react-dom/server'
import App from './App'

ReactDOMServer.renderToString(<App />)
This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.
The new static getDerivedStateFromProps() lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update state, or null to indicate that the new props do not require any state updates.
class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {
    // ...
  }
}
This lifecycle method along with componentDidUpdate() covers all the use cases of componentWillReceiveProps()
Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.
 
One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:
const PureRenderMixin = require('react-addons-pure-render-mixin')

const Button = React.createClass({
  mixins: [PureRenderMixin],
  // ...
})
By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
component.forceUpdate(callback)
It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components.

The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().
If you try to render a <label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.
<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
Since for is a reserved keyword in JavaScript, use htmlFor instead.
<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
You can use spread operator in regular React:
<button style={{...styles.panel.button, ...styles.panel.submitButton}}>{'Submit'}</button>
If you're using React Native then you can use the array notation:
<button style={[styles.panel.button, styles.panel.submitButton]}>{'Submit'}</button>
You can use React.version to get the version.
const REACT_VERSION = React.version

ReactDOM.render(
  <div>{`React version: ${REACT_VERSION}`}</div>,
  document.getElementById('app')
)
You just need to use HTTPS=true configuration. You can edit your package.json scripts section:
"scripts": {
  "start": "set HTTPS=true && react-scripts start"
}
or just run set HTTPS=true && npm start
Add a listener on the history object to record each page view:
history.listen(function (location) {
  window.ga('set', 'page', location.pathname + location.search)
  window.ga('send', 'pageview', location.pathname + location.search)
})
ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.
 
Another popular plugin is eslint-plugin-jsx-a11y, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt text and tabindex, for example, will not be picked up by regular plugins.
A history instance has two methods for navigation purpose.
 
* push()
* replace()

If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.
A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below
<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/user" component={User}/>
  <Route component={NotFound} />
</Switch>
The react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.
import React, { Component } from 'react'
import { Redirect } from 'react-router'

export default class LoginComponent extends Component {
  render() {
    if (this.state.isLoggedIn === true) {
      return <Redirect to="/your/redirect/page" />
    } else {
      return <div>{'Login Please'}</div>
    }
  }
}
The React Intl library makes internalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. React Intl is part of FormatJS which provides bindings to React via its components and API.
It must have one JSX element present so that the task can be accomplished easily. Having more than one expression is not an issue but probably it will slow down the process. There are also chances of confusion with more than one expression if you are new to this technology.
Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props. Hooks allow to easily manipulate the state of our functional component without needing to convert them into class components.
 
Hooks don’t work inside classes (because they let you use React without classes). By using them, we can totally avoid using lifecycle methods, such as componentDidMount, componentDidUpdate, componentWillUnmount. Instead, we will use built-in hooks like useEffect .
Explain what is the use of useState(0) there:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

useState is one of build-in react hooks. useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state.

We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.
Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing components.
React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.
 
React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood.
Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.
Controlled component is more advisable to use as it is easier to implement forms in it. In this, form data are handled by React components. A controlled input accepts values as props and callbacks to change that value.
 
uncontrolled component is a substitute for controlled components. Here form data is handled by DOM itself. In uncomfortable components, the ref can be used to get the form values from DOM.
You can utilize redux-thud middleware which enables you to characterize async activities.
 
How about we take a case of bringing explicit record as an AJAX call utilizing get API:
trade work fetchAccount(id) {
 return dispatch => {
   dispatch(setLoadingAccountState())/Show a stacking spinner
   get(‘/account/${id}’, (reaction) => {
   dispatch(doneFetchingAccount())/Hide stacking spinner
   on the off chance that (response.status === 200) {
   dispatch(setAccount(response.json))/Use an ordinary capacity to set the got state
   } else {
     dispatch(someError)
    }
 })
 }
}
work setAccount(data) {
return { type: ‘SET_Account’, information: information }
}​