300+ React Interview Questions 🔥

Do you want to make a career change to something more lucrative? Or have you been putting in a lot of time and effort in preparation for an interview the following weekend? Do you know how many people are rejected in interviews because they only prepar…


This content originally appeared on DEV Community and was authored by Pramit Marattha

Do you want to make a career change to something more lucrative? Or have you been putting in a lot of time and effort in preparation for an interview the following weekend? Do you know how many people are rejected in interviews because they only prepare for concepts rather than focusing on the real questions that will be asked? This time, avoid being that person. This is the most comprehensive collection of React JS interview questions you'll ever find. It includes a large number of often requested and crucial React JS interview questions and answers. Freshers, seasoned professionals, senior developers, and testers will benefit from a wide range of questions that cover not only the fundamentals of React JS but also the most advanced and challenging problems. This blog post will guide thoroughly for those who want to practice and enhance their react.js skills. I recommend that you read everything thoroughly beforehand and practice and sharpen your react knowledge.

React Basics

1. 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 or 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'
)

2. How to create components in React?

components

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

4. What are Pure Components?

pure components

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. 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 invoked.

5. What is the state in React?

The stateof 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 a user component with a 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>
    )
  }
}

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.

  1. What are props in React?

Propsare 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 the following component functionality:

  • Pass custom data to your component.

  • Trigger state changes.

  • Use via this.props.reactProp inside component render() method

For example, let us create an element with reactProp 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

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 components. Props get passed to the component similar to function parameters whereas the state is managed within the component similar to variables declared within a function.

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 theconstructor or using the latest javascript's class field declaration syntax.

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

react 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'))

10. 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 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 "activateLasers" function in the first point for example)

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

There are 3 possible ways to achieve this:

Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies to React event handlers defined as class methods. Normally we bind them 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.

12. What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper around the browser's native event. Its API is the same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

Synthetic events

13. What is the "key" prop and what is the benefit of using it in arrays of elements?

Keys

A key is a special string attribute you should include when creating arrays of elements.Keyprop helps React identify which items have changed, are added, or are 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 itemindex as a key as a last resort:

14. What is Lifting State Up in React?

Lifting state

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 parent instead of maintaining local state in both of the child components.

15. 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.

16. 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.
React portals

17. What are stateless components?

If the behaviour is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid this keyword altogether.

stateless components

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

If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization of state from props only runs when the component is first created.The below component won't display the updated input value:

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 Router

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

A history instance has two methods for navigation purposes.

Navigation purpose

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.

20. How do you programmatically navigate using React Router v4?

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 component and render props pattern:The component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.

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

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

The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementations. So the decision has been given to users to choose the implementation they like. The recommended approach is to use the query strings library.

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.

React Redux

22. What are Redux selectors and why use them?

Selectorsare 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

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

There are a few ways of binding action creatorsto 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.

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

component vs container

The component is a class or function component that describes the presentational part of your application.The container is an informal term for a component that is connected to a Redux store. Containerssubscribe to Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.

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

redux saga

Saga is like a separate thread in your application, that's solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.

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

27. What is Redux Thunk?

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.

28. 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

We have created a completely free eBook for you to download in the link below because we are unable to add all 300+ complete lists of questions due to character limitations.

https://aviyel.gumroad.com/l/300-plus-react-interview-questions

Discord Link

This eBook 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. This is the most complete React JS interview questions book available. It has a lot of essential and often asked React JS interview questions and answers. Freshers, seasoned professionals, senior developers, and testers will benefit from a wide range of questions that cover not only the basics of React JS but also the most advanced questions. Cheers!! Happy coding and Best of Luck !!


This content originally appeared on DEV Community and was authored by Pramit Marattha


Print Share Comment Cite Upload Translate Updates
APA

Pramit Marattha | Sciencx (2021-11-16T09:43:11+00:00) 300+ React Interview Questions 🔥. Retrieved from https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/

MLA
" » 300+ React Interview Questions 🔥." Pramit Marattha | Sciencx - Tuesday November 16, 2021, https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/
HARVARD
Pramit Marattha | Sciencx Tuesday November 16, 2021 » 300+ React Interview Questions 🔥., viewed ,<https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/>
VANCOUVER
Pramit Marattha | Sciencx - » 300+ React Interview Questions 🔥. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/
CHICAGO
" » 300+ React Interview Questions 🔥." Pramit Marattha | Sciencx - Accessed . https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/
IEEE
" » 300+ React Interview Questions 🔥." Pramit Marattha | Sciencx [Online]. Available: https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/. [Accessed: ]
rf:citation
» 300+ React Interview Questions 🔥 | Pramit Marattha | Sciencx | https://www.scien.cx/2021/11/16/300-react-interview-questions-%f0%9f%94%a5/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.