React Interview Questions| Most Asked Questions For Interview

8499
React Interview Questions
React Interview Questions

React Interview Questions | Most Asked Questions For Interview

React Interview Questions set 1

#1What are the features of React? 

Major features of React are listed below:

  • It uses the virtual DOM instead of the real DOM considering that RealDOM manipulations are expensive.
  • It uses server-side rendering.
  • It follows a uni-directional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

#2 What is React?

React is an open-source front-end JavaScript library that is used for building user interfaces especially for single-page applications. It is used for handling the view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.

#3 What is JSX?

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

#4 How to loop inside JSX?

You can simply use Array.prototype.map with ES6 arrow function syntax.

For example, the items an array of objects is mapped into an array of components:

 <tbody>
 {items.map(item => <SomeComponent key={item.id} name={item.name} />)}
</tbody>

But you can’t iterate using for loop:

 <tbody>
  for (let i = 0; i < items.length; i++) {
    <SomeComponent key={items[i].id} name={items[i].name} />
  }
</tbody>

This is because JSX tags are transpiled into function calls, and you can’t use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.

#5 Explain the purpose of render() in React.

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. This is an important React Interview Questions

#6 Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX is 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.

React Interview Questions

#7 What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

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

#9 What is a state in React?

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

The state is similar to props, but it is private and fully controlled by the component. i.e, It is not accessible to any component other than the one that owns and sets it.

#10 What are props in React?

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

  1. Pass custom data to your component.
  2. Trigger state changes.
  3. 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

#11 What is the difference between state and 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 the component. 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. This is an important React Interview Questions

#12  What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, keypress, etc. Handling these events is similar to handling events in DOM elements. But there are some syntactical differences like:

  1. Events are named using a camel case instead of just using the lowercase.
  2. Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

#13 How to pass a parameter to an event handler or callback?

You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

This is an equivalent to calling .bind:

<button onClick={this.handleClick.bind(this, id)} />

Apart from these two approaches, you can also pass arguments to a function which is defined as an array function

<button onClick={this.handleClick(id)} />
handleClick = (id) => () => {
     console.log("Hello, your ticket number is", id)
};

#14 What are inline conditional expressions?

You can use either if statements or ternary expressions that are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

 <h1>Hello!</h1>
{
    messages.length > 0 && !isLogin?
      <h2>
          You have {messages.length} unread messages.
      </h2>
      :
      <h2>
          You don't have unread messages.
      </h2>
}

#15 What is the use of refs?

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 direct access to the DOM element or an instance of a component.

#16 Explain Flux.

Flux is an architectural pattern that enforces the uni-directional data flow. It controls derived data and enables the communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

React Interview Questions

#17 What are the controlled components?

A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function.

For example, to write all the names in uppercase letters, we use handleChange as below,

handleChange(event) {    
this.setState({value: event.target.value.toUpperCase()})
}

#18 What is the difference between createElement and cloneElement?

JSX elements will be transpired toReact.createElement()functions to create React elements that are going to be used for the object representation of UI. WhereascloneElementis used to clone an element and pass it new props.

#19 How to create props proxy for the HOC component?

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

#20 What is the context?

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)

#21 What are fragments?

It’s a common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

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

There is also a shorter syntax, but it’s not supported in many tools:

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

#22 How to use styles in React?

The style the attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, which is more efficient and prevents XSS security holes.

 const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')'
};
 
function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>
}

Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage).

#23 How you implement Server Side Rendering or SSR?

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.

#24 What is the strict mode in React?

React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment><StrictMode> does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.

import React from 'react'
 
function ExampleApplication() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
          <ComponentOne />
          <ComponentTwo />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  )
}

In the example above, the strict mode checks apply to <ComponentOne> and <ComponentTwo> components only.

#25}What is the arrow function in React? How is it used?

Arrow functions are more of a brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow us to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are most useful while working with the higher-order functions.          

//General way 
Reander(){               
Return(
            <MyInput onChange={this .handleChange.bind(this)}/>
);
}


//With arrow Function
Reander(){               
Return(
            <MyInput onChange={(e)this .handleChange.bind(e)}/>
);
}

Check out the Latest Jobs for ReactJS Developer: Link

Join WhatsApp and Telegram groups for daily job updates: Link

Prepare for Technical Round with Interview Questions: Link

Get insights into HR Interview Questions: Link

Craft a standout resume for Quick shortlisting: Link

Mock Test with Aptitude and Coding Assessment: Click Here

Understand Recruitment Process, Test, and Exam Pattern: Link

Explore Global Opportunities for Professionals & Freshers Abroad: Link

TCS NQT 2023 Careers: Graduate Trainee Hiring: Link 

PwC Internships 2023: Opportunities in Zurich, Switzerland: Link

Chandrayaan 3: India’s Upcoming Lunar Mission Expectations: Link