React Interview Questions 2021: 50 Most Asked Questions & Answers

React Interview Questions 2021: 50 Most Asked Questions & Answers

Looking for React interview questions for freshers and experienced? Here is a list of basic and advanced react interview questions.

In the world of programming, it is impossible to ignore the popularity of React. This JavaScript library is well-known around the world, and several industries are working on it. Regardless of whether you're a professional programmer or a beginner, knowing React will put you on top in your career.

If your goal is to be a React developer, then you surely need to prepare for the job interview process. We will discuss some react interview questions in this blog that will help you pass the interview round.

Concerning the demand for React at the present time, It is highly recommended to learn React native for app development in 2021.

React Interview Questions For Beginners and Experienced

1. What is React?

Answer: React is an open-source front-end JavaScript library used for building user interfaces primarily for single-page applications. Apps that run on the web or mobile devices rely on it to manage their view layer. It was created by a software engineer at Facebook, Jordan Walke. Facebook first deployed React on its News Feed in 2011 and Instagram in 2012.

2. What are the main features of React?

Answer: The main features of React are:

  • Because RealDOM manipulation is extremely expensive, it uses VirtualDOM instead.
  • Server-side rendering is supported.
  • Flows or binds data in a unidirectional manner.
  • Develops the view using reusable/composable UI components.

3. What are the advantages of React?

Answer: The following are the main advantages of React:

  • Virtual DOM improves the performance of an application.
  • JSX makes it easy to read and write code.
  • React renders both on the client and server-side (SSR).
  • Since it is only a view library, it is easy to integrate with frameworks (Angular, Backbone).
  • Jest makes it easy to write unit and integration tests.

4. What are the limitations of React?

Answer: In addition to its advantages, React also has some limitations,

  • Not a full framework, React is just a view library.
  • A learning curve exists for beginners who are new to web development.
  • It requires some additional configuration to integrate React into a traditional MVC framework.
  • With inline templating and JSX, code complexity increases.
  • Overengineering or boilerplate due to too many smaller components.

5. What is JSX?

Answer: JavaScript XML (JSX) is an XML-like extension to ECMAScript. This merely provides syntactic sugar to the React.createElement() function, giving React the expressiveness of JavaScript as well as HTML-like template syntax.

6. How to create components in React?

Answer: It is possible to create a component in two ways.

1. Function Component: This is the simplest method for creating a component. These are pure JavaScript functions that take a props object as the first parameter and return React elements:

function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>
}

2. Class Components: Components can also be defined using ES6 classes. As an example, consider the following function component:

class Greeting extends React.Component {
  render() {
    return <h1>{`Hello, ${this.props.message}`}</h1>
  }
}

7. What is the difference between Element and Component?

Answer: An Element is a simple object that describes what will show up on the screen in terms of the DOM nodes or other components. Elements can have other elements as props. Creating a React element is cheap. It is impossible to mutate an element once it is created.

There are several ways to declare a component. A class with a render() method or a function can be defined. Both methods take props as input and return a JSX tree as output.

8. When to use a Class Component over a Function Component?

Answer: Use a class component if the component needs state or lifecycle methods, otherwise, use a function component. In React 16.8, Hooks were introduced, which enabled you to use state, lifecycle methods, and other features that were previously only available in-class components.

9. What is State in React?

Answer: Each component has a state object that holds data that changes over the lifetime of the component. As much as possible, we should minimize the number of stateful components and keep our state simple.

State is similar to props, except that it is private and fully controlled by the component. In other words, it is not accessible to any other component until the owner component passes it on.

10. What are props in React?

Answer: Props are inputs into components. They are single values or objects containing a set of values that are passed to components when they are created, using a naming convention similar to HTML-tag attributes. These are data that is passed from parent to child components.

In React, props provide the following functionality:

  • You can pass custom data to your component.
  • Trigger changes to the state.
  • You can use this.props.reactProp inside a component's render() method.

11. What is the difference between state and props?

Answer:Props and state are both JavaScript objects. They both hold information that influences the output of render, but their functions concerning components differ. Props get passed to the component similarly to function parameters, whereas state is managed within the component similarly to variables declared within a function.

12. What are Pure Components?

Answer: React.PureComponent is the same as React.Component, but it handles the shouldComponentUpdate() method for you. Whenever props or states change, PureComponent will conduct a shallow comparison on both props and states. On the other hand, components will not compare current props and state to the next instance. Therefore, the component will re-render by default whenever shouldComponentUpdate is called.

13. Why should we not update the state directly?

Answer: Directly updating the state will not re-render the component. Use the setState() method instead. The component's state object is scheduled for an update. Whenever a state changes, the component responds by re-rendering.

this.setState({ message: 'Hello World' })

14. What are synthetic events in React?

Answer: In other words, SyntheticEvent is a cross-browser wrapper around native events in the browser. Its API is identical to that of the browser's native event, including stopPropagation() and preventDefault(), but the events work identically in all browsers.

15. What is the use of refs?

Answer: References to elements are returned by the ref. While they should generally be avoided, they can be useful when accessing a DOM element or instance of a component directly.

16. What are inline conditional expressions?

Answer: In JS, you can use either if statements or ternary expressions to render expressions conditionally. Apart from these approaches, you can also embed any expression in JSX by wrapping it in curly braces and then followed by the JS logical operator &&.

17. What is the difference between HTML and React event handling?

Answer: Here are some of the main differences between HTML and React event handling:

1.) As a convention, HTML events are usually written in lowercase:

<button onclick='activateLasers()'>

On the other hand, in React it follows camelCase:

<button onClick={activateLasers}>

2.) You can return false in HTML to prevent default behavior:

<a href='#' onclick='console.log("The link was clicked."); return false;' />

In React, you must explicitly call preventDefault():

function handleClick(event) {
  event.preventDefault()
  console.log('The link was clicked.')
}

3.) HTML functions are invoked by appending(). However, in React, you should not append() with the function name. (refer to "activateLasers" function in the first point, for instance)

18. Why is String Refs legacy?

Answer: When you worked with React before, you might be familiar with an old API where the ref attribute as a string, such as ref={'textInput'}, and the DOM node was accessed as this.refs.textInput. Our recommendation is to avoid string refs since they have problems below, and are considered legacy. React v16 removed string refs.

  1. React is forced to keep track of the currently executing components. As a result, react modules become stateful, causing strange errors when react modules are duplicated in the bundle.

  2. A user can't add another ref to the passed child if a library has already put a ref on it. Callback refs are completely composable.

  3. They don't use static analysis like Flow. The magic that framework uses to make the string ref appear on this.refs and its type (which might be different) is beyond Flow's understanding. Static analysis is more friendly to callback refs. The "render callback" pattern (e.g.) does not work as expected.

19. What is Virtual DOM?

Answer: A VirtualDOM (VDOM) is an in-memory representation of a RealDOM. Based on the representation of a UI in memory, the "real" DOM is synced with the VDOM. It's a step that happens between the render function being called and displaying elements on the screen. All of this is known as reconciliation.

20. How Virtual DOM works?

Answer: Three simple steps are involved in the Virtual DOM.

  • When any underlying data changes, all UI elements are re-rendered in a Virtual DOM representation.
  • The difference between the previous and new DOM representations is then calculated.
  • Once the calculations are completed, only the elements that have changed will be in the actual DOM.

21. What is the difference between Shadow DOM and Virtual DOM?

Answer: As a browser technology, Shadow DOM is used primarily to scope variables and CSS in web components. JavaScript libraries implement the Virtual DOM concept on top of browser APIs.

22. What are controlled components?

Answer: Components that control the input elements on subsequent user input are called Controlled Components, i.e., every state mutation will have a handler function.

23. What are uncontrolled components?

Answer: Uncontrolled Components are those that store their state internally, and you use a ref to query the DOM when you need to find its current value. As you can see, this is a bit more traditional HTML.

24. What is context?

Answer: Context offers a way to pass data through the component tree without the necessity to pass props down manually at every level.

For example, many components in the application require access to authenticated users, locale preferences, and UI themes.

const {Provider, Consumer} = React.createContext(defaultValue)

25. What is children prop?

Answer: It is possible to pass components to other components as data using the children prop (this.props.children). Component tree placed between component's opening and closing tag will be passed to that component as a child prop.

The React API has a number of methods for working with this prop. These are React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.

26. What is reconciliation?

Answer: In React, when the state or props of a component change, it compares the recently returned element with the previously rendered one to determine whether an actual DOM update is required. React will update the DOM when they are not equal. It is called reconciliation.

27. Why React uses className over class attribute?

Answer: JavaScript uses the class keyword, and JSX is an extension of JavaScript. React uses className instead of class because of this reason. As the className prop, pass a string.

render() {
  return <span className={'menu navigation-menu'}>{'Menu'}</span>
}

28. What are fragments?

Answer: Components can return multiple elements by using this pattern in React. Fragments allow you to group a list of children without adding any extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  )
}

29. Why fragments are better than container divs?

Answer: Here is a list of reasons why fragments are better than container divs:

  1. By not creating an extra DOM node, fragments are a bit faster and use less memory. This is only useful for large, deep trees.
  2. CSS mechanisms like Flexbox and CSS Grid have a unique parent-child relationship, and adding divs in the middle makes it difficult to keep the desired layout.
  3. Less cluttered DOM Inspector

30. What is React Fiber?

Answer: It is the new reconciliation engine or reimplementation of the core algorithm introduced in React 16. Its purpose is to improve its suitability for areas such as animation, layout, gestures, the ability to pause, abort, or reuse work, and new concurrency primitives.

31. What is the main goal of React Fiber?

Answer: React Fiber aims to enhance its suitability for areas like animation, layout, and gestures. Incremental rendering is its most prominent feature: the ability to break up rendering tasks into smaller pieces and spread them over several frames. Based on the documentation, its main goals are:

  • Splitting interruptible work into chunks is possible.
  • It is possible to prioritize, rebase, and reuse work in progress.
  • Support for yielding back and forth between parents and children in React.
  • Multiple elements can be returned from render().
  • Improved error boundary support.

32. What are Higher-Order Components?

Answer: Higher-order components (HOC) take a component and return another new component. Based on the compositional nature of React, it's a pattern.

We call them pure components because they accept any child component provided dynamically but won't modify or copy their input component's behavior.

There are many use cases for HOC:

  • Render hijacking
  • Props manipulation
  • Code reuse, logic, and bootstrap abstraction.
  • State abstraction and manipulation.

33. How to write comments in React?

Answer: Similar to JavaScript Multiline comments, React/JSX comments are wrapped in curly braces.

  • For Single-line comments:
<div>
  {/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
  {`Welcome ${user}, let's play React`}
</div>
  • For Multiple-line comments:
<div>
  {/* Multi-line comments for more than
   one line */}
  {`Welcome ${user}, let's play React`}
</div>

34. What is flux?

Answer: The Flux paradigm replaces the more traditional MVC pattern in application design. Rather than a framework or library, it is a whole new approach to the concept of Unidirectional Data Flow that complements React. When working with React, Facebook uses this pattern internally.

35. What is Redux?

Answer: Based on the Flux design pattern, Redux is a predictable state container for JavaScript apps. With Redux, you can use React or any other view library. It is small (about 2kB) and independent.

36. What are stateful components?

Answer: When the behavior of a component depends on the state of the component, it is called a stateful component. Stateful components are always class components with a constructor that initializes the state.

37. What are stateless components?

Answer: If a component's behavior is independent of its state, then it can be considered a stateless component. When creating stateless components, you can either use functions or classes. In any case, unless you require a lifecycle hook for your components, function components should be used. The benefits of using function components here are many; they are easy to write, understand, and test, a little faster, and you can eliminate this keyword.

38. What is the use of the react-dom package?

Answer: React-dom provides methods specific to the DOM that can be used at the top level of your application. This module does not require most of the components. This package contains the following methods:

  • render()
  • hydrate()
  • unmountComponentAtNode()
  • findDOMNode()
  • createPortal()

39. What is the difference between React and ReactDOM?

Answer: React package provides React.createElement(), React.Component and React.Children, among other helpers related to elements and component classes. In terms of building components, you can consider these as isomorphic or universal helpers.

Within the react-dom package, we have ReactDOM.render(), and within react-dom/server, we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

40. What is ReactDOMServer?

Answer: Using the ReactDOMServer object, you can render components to static markup (typically used on a node server). It is used primarily for server-side rendering (SSR). Both server and browser environments can use the following methods:

  • renderToString()
  • renderToStaticMarkup()

41. ReactDOM and React are separate components. Why?

Answer: React's team extracted all DOM-related functionality into a separate library called ReactDOM. The libraries are split for the first time in React v0.14. In looking at some of the packages, react-native, react-art, react-canvas, and react-three, it becomes clear that the essence of React has nothing to do with browsers or the DOM.

React team planned to split the React package into two components: react and react-dom, to render React to more environments. Using this approach, components can be written that can be shared between the web and native versions of React.

42. What is React Router?

Answer: A routing library built on top of React, React Router allows you to add new screens and flows to your application incredibly quickly while keeping the URL and the content of the page in sync.

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

Answer: React is an open-source front-end JavaScript library used for building user interfaces primarily for single-page applications.

You can build native mobile applications (iOS, Android, and Windows) using React Native, a mobile framework that enables you to build native components and implements React under the hood.

44. How to test React Native apps?

Answer: Mobile simulators like iOS and Android are the only way to test React Native. The app can be run on your mobile device by using the expo app. Because it syncs via QR code, your device and computer should be on the same wireless network.

45. How error boundaries handled in React v15?

Answer: The unstable_handleError method in React v15 provides very basic support for error boundaries. React v16 renamed it to componentDidCatch.

Answer: For type checking in React applications, we use the PropTypes library (React.PropTypes has moved to the prop-types package since React 15.5). When dealing with large codebases, static type checking tools such as Flow or TypeScript are recommended, as they perform type checking at compile time with auto-completion.

47. What is the lifecycle methods order in mounting?

Answer: When a component instance is created and inserted into the DOM, the following lifecycle methods are called.

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

48. How you implement Server Side Rendering or SSR?

Answer: Node servers are already capable of handling React rendering. There is a special version of the DOM renderer that uses the same pattern as the client-side version.

import ReactDOMServer from 'react-dom/server'
import App from './App'

ReactDOMServer.renderToString(<App />)

The regular HTML will be output as a string, which can then be placed inside a page body as part of the server response. Detecting the pre-rendered content on the client-side, React seamlessly continues where it left off.

49. What are React Mixins?

Answer: To achieve common functionality, mixins allow components to be totally separated. Instead of using mixins, higher-level components or decorators should be used.

PureRenderMixin is one of the most commonly used mixins. You might be using it in some components to prevent unnecessary re-rendering when the props and state are superficially equal to the previous props and state:

const PureRenderMixin = require('react-addons-pure-render-mixin')

const Button = React.createClass({
  mixins: [PureRenderMixin],
  // ...
})

50. What are the Pointer Events supported in React?

Answer: Pointer Events are a unified way of handling all input events. In the past, we had a mouse and their respective event listeners to handle them, but nowadays we have many devices that don't correlate with a mouse, such as phones with touch screens or pens. You must keep in mind that these events only work with browsers that support Pointer Events specifications.

React DOM now supports the following event types:

  • onPointerDown
  • onPointerMove
  • onPointerUp
  • onPointerCancel
  • onGotPointerCapture
  • onLostPointerCapture
  • onPointerEnter
  • onPointerLeave
  • onPointerOver
  • onPointerOut

If you have made it this far, then certainly you are willing to learn more about React. Here are some more resources related to React that we think will be useful to you.

Did you find this article valuable?

Support Yash Tiwari by becoming a sponsor. Any amount is appreciated!