Instagram
youtube
Facebook
  • 10 months, 3 weeks ago
  • 4516 Views

Infosys React.js Interview Questions and Answers

Aadesh Shrivastav
Table of Contents

Explore a comprehensive guide to Infosys React.js Interview Questions and Answers, designed to help you succeed in your technical interviews. Whether you're a seasoned developer or preparing for your first React.js job interview at Infosys, this resource covers a range of topics, including React.js fundamentals, state management, component lifecycle, and more. Gain insights into the types of questions frequently asked by Infosys interviewers and equip yourself with the knowledge and confidence needed to excel. Elevate your React.js skills and enhance your preparation with this valuable resource tailored for Infosys interviews.

Q1. Explain Presentation component and Functional component.

Ans: In React.js, the terms "presentation component" and "functional component" are often used interchangeably, but they refer to different concepts. Let's break down these terms:

1. Functional Component:

  • A functional component in React is a JavaScript function that returns a React element.
  • Functional components were initially stateless and used for simple UI components. They don't have their own internal state or lifecycle methods.
  • With the introduction of React Hooks in React 16.8, functional components can now have state and use other features that were exclusive to class components.

Example of a functional component:

import React from 'react';

const FunctionalComponent = (props) => {

  return (

    <div>

      <p>Hello, {props.name}!</p>

    </div>

  );

};

export default FunctionalComponent;

2. Presentation Component:

  • A presentation component is a concept more related to the role a component plays in the architecture of an application rather than its implementation details.
  • Presentation components are also referred to as "dumb" or "stateless" components. They are primarily concerned with how things look and don't manage their own state or interact with data.
  • They receive data and behavior via props and focus on rendering UI elements.

Example of a presentation component:

import React from 'react';

const FunctionalComponent = (props) => {

  return (

    <div>

      <p>Hello, {props.name}!</p>

    </div>

  );

};

export default FunctionalComponent;

In this example, PresentationComponent is a stateless component that receives data via props and renders it. It doesn't manage any internal state or handle complex logic.

It's worth noting that with the introduction of React Hooks, functional components can now handle state and lifecycle methods, blurring the lines between functional and class components. The emphasis is more on the role a component plays in the application architecture rather than whether it is implemented as a function or a class. Additionally, the term "functional component" is still commonly used, even when the component uses Hooks and has state.

In modern React development, functional components with Hooks are widely used due to their simplicity and the ability to handle state and side effects. However, the choice between functional and class components often depends on the specific needs of the component and the development team's preferences.

 

Q2. What is hoisting?

Ans: Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use variables and functions in your code before they are declared in the source code. However, it's important to note that only the declarations are hoisted, not the initializations.

Let's look at examples to illustrate hoisting with variables and functions:

Variable Hoisting:

console.log(x); // undefined
var x = 5;
console.log(x); // 5

In the above example, even though console.log(x) appears before the variable x is declared, JavaScript hoists the declaration to the top, and the output is undefined rather than causing an error.

Function Hoisting:

hello(); // "Hello, World!"

function hello() {
  console.log("Hello, World!");
}

In this example, the function hello is called before its declaration, and it works without an error. The function declaration is hoisted to the top of the script or function.

Note on Initialization:

It's important to understand that only the declarations are hoisted, not the initializations. For example:

console.log(y); // undefined
var y = 10;
console.log(y); // 10

In this case, the variable y is hoisted, but its initialization (y = 10) remains in the original order. The first console.log(y) outputs undefined, and the second one outputs 10.

Hoisting with let and const:

Variables declared with let and const are also hoisted, but they are not initialized with undefined as in the case of var. This is often referred to as the "temporal dead zone." For example:

console.log(z); // ReferenceError: Cannot access 'z' before initialization
let z = 20;

Here, z is hoisted, but accessing it before the declaration results in a ReferenceError.

In conclusion, hoisting is a concept in JavaScript that allows you to use variables and functions before their declarations in the source code, but it's crucial to understand the details of how hoisting works to avoid potential issues in your code.

 

Q3. What is function currying?

Ans: Function currying is a technique in functional programming where a function with multiple parameters is transformed into a sequence of functions, each taking a single parameter. The curried function allows you to partially apply arguments, creating new functions with fewer parameters.

In simpler terms, function currying involves breaking down a function that takes multiple arguments into a series of functions, each handling one argument at a time.

Here's an example in JavaScript to illustrate currying:

// Non-curried function
function add(x, y, z) {
  return x + y + z;
}

console.log(add(2, 3, 4)); // Output: 9

// Curried version
function curryAdd(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    };
  };
}

console.log(curryAdd(2)(3)(4)); // Output: 9

// Using a more concise syntax (currying with arrow functions)
const arrowCurryAdd = x => y => z => x + y + z;

console.log(arrowCurryAdd(2)(3)(4)); // Output: 9

In the example above:

  • The non-curried function add takes three parameters and returns their sum.
  • The curried version curryAdd is a series of nested functions. Each function takes one parameter and returns a new function that expects the next parameter.
  • The curried version with arrow functions (arrowCurryAdd) provides a more concise syntax for the same behavior.

One benefit of function currying is the ability to create more specialized and reusable functions. You can partially apply arguments to create new functions, making it easier to create variations of a function with specific configurations.

Here's an example of partial application with currying:

const add5 = curryAdd(5); // Partial application

const result = add5(3)(4); // Equivalent to add(5, 3, 4)

console.log(result); // Output: 12

Function currying is a powerful concept in functional programming, and it's often used in libraries and frameworks that embrace a functional programming paradigm. It provides a way to create flexible and composable functions.

 

Q4. What is Virtual DOM in React.js?

Ans: In React.js, the Virtual DOM (Document Object Model) is a programming concept where an ideal or "virtual" representation of the user interface is kept in memory. It's a lightweight copy of the actual DOM present in the browser.

Here's how the Virtual DOM works in React:

1. Initialization: When a React component is initially rendered, React creates a virtual representation of the DOM.

2. Render: When the state of a React component changes, a new virtual DOM tree is created. This new tree represents the updated state and how the UI should look.

3. Diffing: React then compares the new virtual DOM with the previous one to identify the differences or changes that occurred.

4. Reconciliation: React calculates the most efficient way to update the actual DOM based on the identified differences. It generates a minimal set of changes needed to update the real DOM.

5. Update: Finally, React updates the real DOM with the minimal set of changes, ensuring that only the necessary parts of the DOM are modified.

The purpose of the Virtual DOM is to optimize and improve the performance of updating the user interface. Instead of directly manipulating the actual DOM for every state change, React performs these operations on the lightweight and faster Virtual DOM. This approach helps reduce the number of direct manipulations on the actual DOM, making updates more efficient and leading to a better user experience.

By using the Virtual DOM, React can achieve a balance between performance and a declarative programming model, where developers describe what the UI should look like for a given state, and React takes care of efficiently updating the DOM to reflect that description.

 

Q5. Explain the lifecycle of React.js?

Ans: In React.js, components go through a series of lifecycle events, from initialization to unmounting. These lifecycle events provide opportunities to perform actions at different stages of a component's existence. React 16.3 introduced a new set of lifecycle methods, often referred to as "React Hooks." Here's an overview of the major lifecycle phases:

Class Component Lifecycle (Legacy Lifecycle):

Mounting Phase:

  • constructor(): Called when the component is initialized. Used for setting initial state and binding event handlers.
  • static getDerivedStateFromProps(): A static method that is called when the component is receiving new props. It returns an object to update the state or null to indicate no state updates are necessary.
  • render(): The only required method in a class component. It returns the JSX that represents the component's UI.
  • componentDidMount(): Called after the component is rendered to the DOM. It's often used for making AJAX requests or setting up subscriptions.

Updating Phase:

  • static getDerivedStateFromProps(): Similar to the mounting phase, this method is called when the component is receiving new props.
  • shouldComponentUpdate(): Returns a boolean indicating whether the component should re-render. Used for performance optimization.
  • render(): Re-renders the component with updated state or props.
  • getSnapshotBeforeUpdate(): Called right before the changes from the virtual DOM are to be reflected in the actual DOM. It allows you to capture information (e.g., scroll position) before the update.
  • componentDidUpdate(): Called after the component is updated in the DOM. Used for side effects, like fetching data based on changed props.

Unmounting Phase:

  • componentWillUnmount(): Called just before the component is removed from the DOM. Used for cleanup operations (e.g., canceling network requests, clearing timers).

Functional Component Lifecycle (Hooks):

In functional components, lifecycle methods are replaced with React Hooks:

  • useState(): Allows functional components to manage state.
  • useEffect(): Combines componentDidMount, componentDidUpdate, and componentWillUnmount. It runs after every render and handles side effects.

These hooks provide a more expressive way to handle component lifecycle events in functional components.

Additional Note:

  • The componentWillReceiveProps() lifecycle method is deprecated and replaced with static getDerivedStateFromProps().
  • componentWillUpdate() is also deprecated and replaced with getSnapshotBeforeUpdate().
  • React 17 introduced an experimental feature called "Async Rendering" that could impact how some lifecycle methods behave.

Always refer to the official React documentation for the most up-to-date information on React component lifecycles.

 

Q6. What are props in React..js?

Ans: In React.js, "props" is short for properties, and it is a special keyword that allows you to pass data from a parent component to a child component. Props are a way to customize or configure a component by passing data to it, similar to how attributes work in HTML.

  • Passing Data:
    • The parent component can pass data to a child component by providing it as attributes when the child component is rendered.
// Parent Component

<ChildComponent name="John" age={25} />
  • Receiving Data:
    • In the child component, you can access these passed values through the props object.
    • In this example, name and age are props that the ChildComponent can access.
// Child Component

const ChildComponent = (props) => {

  return (

    <div>

      <p>Name: {props.name}</p>

      <p>Age: {props.age}</p>

    </div>

  );

};
  • Immutable:
    • Props are immutable, meaning that a child component cannot modify the values passed to it via props. They are read-only.
  • Dynamic Data:
    • Props allow you to create dynamic and reusable components. By changing the props, you can control what content or behavior a component should have.
// Parent Component

const App = () => {

  return <ChildComponent name="John" age={25} />;

};

// Child Component

const ChildComponent = (props) => {

  return (

    <div>

      <p>Name: {props.name}</p>

      <p>Age: {props.age}</p>

    </div>

  );

};

In the example above, name and age are passed as props from the App component to the ChildComponent, allowing the child component to display the data provided by the parent.
 

Q7. How to create components in React?

Ans: Creating components in React involves defining reusable, self-contained pieces of UI that can be composed to build complex user interfaces. There are two main types of components in React: functional components and class components. Here's how you can create each type:

Functional Components:

Functional components are simpler and more concise. They are basically JavaScript functions that take in props as an argument and return React elements.

// Example of a functional component
import React from 'react';

const MyFunctionalComponent = (props) => {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>This is a functional component.</p>
    </div>
  );
};

export default MyFunctionalComponent;

Class Components:

Class components are ES6 classes that extend from React.Component. They have a render method where you define the component's UI.

// Example of a class component
import React, { Component } from 'react';

class MyClassComponent extends Component {
  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}!</h1>
        <p>This is a class component.</p>
      </div>
    );
  }
}

export default MyClassComponent;

Usage in Other Components:

Once you've created your components, you can use them in other components or in your main application file. For example:

import React from 'react';
import MyFunctionalComponent from './MyFunctionalComponent';
import MyClassComponent from './MyClassComponent';

const App = () => {
  return (
    <div>
      <MyFunctionalComponent name="John" />
      <MyClassComponent name="Jane" />
    </div>
  );
};

export default App;

Remember to export your components so that they can be imported and used in other parts of your application.

Choose between functional and class components based on your needs. Functional components are preferred for simplicity, while class components offer additional features like local state and lifecycle methods. With React Hooks, functional components can also manage state and side effects effectively.

Add a comment: