React Interview Questions 🔥

Table of Contents

React Interview Questions: This is the most complete set of React JS interview questions you’ll ever come across. It has a lot of often asked and important React JS interview questions and answers. A wide range of questions will benefit freshmen, seasoned professionals, senior developers, and testers, covering not only the fundamentals of React JS but also the most sophisticated and tough problems. This blog article will provide detailed instructions for anyone wishing to practice and improve their react.js skills. I urge that you properly read everything ahead of time and practice and sharpen your reaction skills.

1. What is the difference between Element and Component?

In terms of the DOM nodes or other components, an Element is a simple object that describes what you wish to see on the screen. Elements can have props that contain other Elements. It is cheap to manufacture a React element. Once an element has been generated, it cannot be changed. React Element’s object representation 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>

A component, on the other hand, can be stated in a variety of ways. It can be defined as a function or as a class having a render() method. It accepts props as an input and returns a JSX tree as an output in any case:

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

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

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

2. How to create components in React?

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 the 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>
 }
}

3. What are Pure Components?

pure components

React. PureComponent is identical to React. Component, with the exception that it takes care of the shouldComponentUpdate() method for you. PureComponent does a shallow comparison on both props and state when they change. Out of the box, components, on the other hand, will not compare current props and states to the next. As a result, anytime shouldComponentUpdate is called, the component will re-render by default.

4. What is the state in React?

A component’s state is an object that contains information that may change over the component’s lifespan. We should always attempt to keep our state as basic as possible, with as few stateful components as possible. Let’s make a user component that has a message state, shall we?

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

The state is similar to props, but it is private and fully controlled by the component. i.e, It is not accessible to any other component until the owner component decides to pass it.

5. What are props in React?

Inputs to components are known as props. They are single values or objects with a set of values that are supplied to components when they are created using a naming scheme similar to HTML-tag attributes. They’re information passed from a parent component to a child component. Props in React are mostly used to offer the following component functionality:

  • Pass custom data to your component.
  • Trigger state changes.
  • Use via this. props.react prop inside component render() method

For example, let us create an element with react prop property:

<Element reactProp={'1'} />

This react pro (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

7. What is the difference between state and props?

state vs props

Props and state are both standard JavaScript objects. While they both contain information that determines render output, their usefulness in terms of components is distinct. Props are supplied to the component in the same way that function parameters are, and the state is managed within the component in the same way that variables specified in a function are.

8. Why should we not update the state directly?

If you try to update the state directly then it won’t re-render the component.

//Wrong
this.state.message = 'Hello world'

Instead, usesetState() method. It schedules an update to a component’s state object. When the state changes, the component responds by re-rendering.

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

Note: You can directly assign to the state object either in the constructor or using the latest javascript’s class field declaration syntax.

9. 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 becomes extremely easy

10. 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 a little difficult for novice programmers to understand
  4. Coding gets complex as it uses inline templating and JSX

11. What is the purpose of the callback function as an argument of setState()?

The callback function is invoked when setState finishes and the component gets rendered. Since setState()is asynchronous the callback function is used for any post action.
Note: It is recommended to use the lifecycle method rather than this callback function.

setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))

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

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

  1. In HTML, the event name is usually represented in lowercase as a convention:
<button onClick={activateLasers}>

Whereas in React it follows camelCase

<button onClick={activateLasers}>
  1. In HTML, you can return false to prevent the default behavior.
<a href='#' onclick='console.log("The link was clicked."); return false;' />

Whereas in React you must call preventDefault() explicitly:

function handleClick(event) {
  event.preventDefault()
  console.log('The link was clicked.')}
  1. In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer to the “activateLasers” function in the first point for example)

13. How to bind methods or event handlers in JSX callbacks?

There are 3 possible ways to achieve this:

Binding in the constructor: The methods in JavaScript classes are not bound by default. React event handlers written as class methods are in the same boat. Normally, they’re bound in the constructor.

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

Public class fields syntax: If you don’t like to use the bind approach then public class fields syntax can be used to correctly bind callbacks.

handleClick = () => {
  console.log('this is:', this)
}

<button onClick={this.handleClick}>
  {'Click me'}
</button>

Arrow functions in callbacks: You can use arrow functions directly in the callbacks.

handleClick() {
    console.log('Click happened');
}
render() {
    return <button onClick={() => this.handleClick()}>Click Me</button>;
}

Note: If the callback is passed as a prop to child components, those components might do an extra re-rendering. In those cases, it is preferred to go with the .bind() or public class fields syntax approach considering performance.

14. What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper for the native event of the browser. Its API is identical to that of the browser’s native event, including stopPropagation() and preventDefault(), with the exception that the events work in all browsers.

15. What is the “key” prop and what is the benefit of using it in arrays of elements?

When generating arrays of elements, you should add a key as a special string attribute. React uses Keyprop to determine which items have changed, have been added, or have been removed. Most often we use the ID from our data askey:

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
)

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

16. What is Lifting State Up in React?

When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to the parent instead of maintaining the local state in both of the child components.

17. How is React different from Angular?

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

18. What are the different phases of the component lifecycle?

The component lifecycle has three distinct lifecycle phases:

  • Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.
  • Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.
  • Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes the componentWillUnmount() lifecycle method.

It’s worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows:

  • Render The component will render without any side effects. This applies for Pure components and in this phase, React can pause, abort, or restart the render.
  • Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate().
  • Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.

19. What are portals in React?

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container)

The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.

20. What are stateless components?

A stateless component is one whose behavior is independent of its state. You can create stateless components with either a function or a class. If you don’t require a lifecycle hook in your components, however, function components are the way to go. If you use function components instead of keywords, you’ll gain a number of benefits: they’re easier to create, comprehend, and test, they’re a little faster, and you won’t have to use this keyword.

21. What will happen if you use props in the initial state?

A stateless component is one whose behavior is independent of its state. You can create stateless components with either a function or a class. If you don’t require a lifecycle hook in your components, however, function components are the way to go. If you use function components instead of keywords, you’ll gain a number of benefits: they’re easier to create, comprehend, and test, they’re a little faster, and you won’t have to use this keyword.

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      records: [],
      inputValue: this.props.inputValue
    };
  }
  render() {
    return <div>{this.state.inputValue}</div>
  }
}

Using props inside the render method will update the value:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      record: []
    }
  }

  render() {
    return <div>{this.props.inputValue}</div>
  }
}

React Interview Questions

22. What is the purpose of push() and replace() methods of history?

A history instance has two methods for navigation purposes.

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.

23. How do you programmatically navigate using React Router ?

There are three different ways to achieve programmatic routing/navigation within components.

Using the withRouter() higher-order function:The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.

import { withRouter } from 'react-router-dom' // this also works with 'react-router-native'

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    {'Click Me!'}
  </button>
))

Using the component and render props pattern: Because the component passes the same props as withRouter(), you may use the history prop to access the history methods.

import { Route } from 'react-router-dom'

const Button = () => (
  <Route render={({ history }) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      {'Click Me!'}
    </button>
  )} />
)

Using context:This option is not recommended and is treated as an unstable API.

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      context.history.push('/new-location')
    }} >
    {'Click Me!'}
  </button>
)
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

24. How to get query parameters in React Router v4?

Because there have been user requests throughout the years to support alternative implementations, the ability to parse query strings was removed from React Router v4. As a result, users have the option to choose the implementation they like. The query strings library is the recommended method.

const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);

You can also use URLSearchParams if you want something native:

const params = new URLSearchParams(props.location.search)
const foo = params.get('name')

You should use apply fill for IE11.

25. What are Redux selectors and why use them?

Selectors are functions that take the Redux state as an argument and return some data to pass to the component. For example, to get user details from the state:

const getUserData = state => state.user.data

These selectors have two main benefits,

The selector can compute derived data, allowing Redux to store the minimal possible state

The selector is not recomputed unless one of its arguments changes

26. What are the different ways to write mapDispatchToProps()?

There are a few ways of binding action creators to dispatch() in mapDispatchToProps().Below are the possible options:

const mapDispatchToProps = (dispatch) => ({
 action: () => dispatch(action())
})
const mapDispatchToProps = (dispatch) => ({
 action: bindActionCreators(actioimport { ADD_TODO } from './actionTypes'
export default (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ];
    default:
      return state
  }
}
n, dispatch)
})
const mapDispatchToProps = { action }

The third option is just a shorthand for the first one.

27. What is the difference between component and container in React Redux?

The presentational aspect of your application is described by the component, which is a class or function component. A component that is connected to a Redux store is referred to as a container. Containers normally don’t render DOM elements since they listen to Redux state updates and dispatch actions, and they delegate rendering to presentational child components.

28. What is the mental model of redux-saga?

Saga functions as a separate thread in your program that is solely responsible for side effects. redux-saga is a redux middleware, which means it can be started, paused, and aborted from the main application using standard Redux actions, has access to the entire Redux application state, and can also dispatch Redux actions.

29. What are the differences between call() and put() in redux-saga?

Both call() and put() are effect creator functions. call() function is used to create effect description, which instructs middleware to call the promise. put() function creates an effect, which instructs middleware to dispatch an action to the store.Let’s take the example of how these effects work for fetching particular user data.

function* fetchUserSaga(action) {
  // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.
  // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
  const userData = yield call(api.fetchUser, action.userId)

  // Instructing middleware to dispatch corresponding action.
  yield put({
    type: 'FETCH_USER_SUCCESS',
    userData
  })
}

30. What is Redux Thunk?

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of action or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch() and getState() as parameters.

31. What are Redux selectors and why use them?

Selectors are functions that take the Redux state as an argument and return some data to pass to the component.For example, to get user details from the state:

const getUserData = state => state.user.data

These selectors have two main benefits,

The selector can compute derived data, allowing Redux to store the minimal possible state

The selector is not recomputed unless one of its arguments changes

32. What is a diffing algorithm?

React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithm is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.In this case, for displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:

  • Two elements of different types will produce different trees.
  • The developer can hint at which child elements may be stable across different renders with a key prop.

33. Is it prop must be named as render for render props?

Despite the fact that the pattern is called render props, you don’t have to utilize a render prop to use it. i.e., a “render prop” is any prop that is a function that a component uses to determine what to render. Let’s look at the children prop for render props as an example.

<Mouse>  
{mouse => (
    <p>The mouse position is {mouse.x}, {mouse.y}</p>
  )}</Mouse>children={mouse => (
  <p>The mouse position is {mouse.x}, {mouse.y}</p>
)}/>

Actually children prop doesn’t need to be named in the list of “attributes” in JSX element. Instead, you can keep it directly inside element,

<<Mouse>  
{mouse => (
    <p>The mouse position is {mouse.x}, {mouse.y}</p>
  )}</Mouse>

While using this above technique(without any name), explicitly state that children should be a function in your propTypes.

Mouse.propTypes = {
  children: PropTypes.func.isRequired
};

34. What are the problems of using render props with pure components?

The objective of the pure component is defeated if you create a function inside a render method. Because for new props, the shallow prop comparison will always return false, and each render in this instance will generate a new value for the render prop, each render will generate a new value for the render prop. This problem can be solved by declaring the render function as an instance method.

Image description

35. How do you create HOC using render props?

You can implement most higher-order components (HOC) using a regular component with a render prop. For example, if you would prefer to have a with Mouse HOC instead of a component, you could easily create one using a regular with a render prop.

function withMouse(Component) {
  return class extends React.Component {
    render() {
      return (
        <Mouse render={mouse => (
          <Component {...this.props} mouse={mouse} />
        )}/>
      );
    }
  }
}

This way to render props gives the flexibility of using either pattern.

36. What is the windowing technique?

Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtualized are popular windowing libraries which provide several reusable components for displaying lists, grids, and tabular data.

37. What is the typical use case of portals?

React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context(z-index,position,opacity etc styles) and you need to visually “break out” of its container.
For example, dialogs, global message notifications, hovercards, and tooltips.

38. How do you set the default value for an uncontrolled component?

The value attribute on form elements overrides the value in the DOM in React. You might want React to specify the initial value for an uncontrolled component, but keep subsequent updates uncontrolled. Instead of value, you can give a defaultValue property to handle this circumstance.

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <label>
        User Name:
        <input
          defaultValue="John"
          type="text"
          ref={this.input} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

The same applies for select and text Area inputs. But you need to use default Checked for checkbox and radio inputs.

39: How to create refs?

Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property with in constructor.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

And:

class UserForm extends Component {
  handleSubmit = () => {
    console.log("Input Value is: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} /> // Access DOM input in handle submit
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

We can also use it in functional components with the help of closures.

40. Why can’t browsers read JSX?

Because browsers can only understand JavaScript objects, and JSX isn’t one of them, they can’t read it directly. As a result, we’ll need to use transpilers like Babel to convert the JSX file into a JavaScript object, which we’ll then send to the browser.

These are all the basic to advanced ReactJS interview questions that are frequently asked in interviews. We hope these ReactJS interview questions will be helpful in clearing your interview round. All the best for your upcoming job interview!

Leave a Comment

Your email address will not be published.