React interview questions

nikhilkalariya

nikhilkalariya

Posted on March 19, 2024

React interview questions

1. What is React?

React is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.

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

2. How is React different from Angular or Vue?
When comparing React, Angular, and Vue.js, a few key differentiators stand out.

Core Philosophy

  • React: Focuses on UI components. You need other libraries for state management, routing, etc.

  • Angular: Provides a more comprehensive solution out of the box, often called "batteries included."

  • Vue.js: A good balance of providing core libraries and flexibility for integration with third-party tools.

Learning Curve

  • React: Initially simpler to learn due to its focused nature, but can become complex as you add more external libraries.

  • Angular: Steeper learning curve because of its complete ecosystem, including modules, services, and complex directives.

  • Vue.js: Known for its gentle learning curve and clear, concise documentation.

Community and Ecosystem

  • React: Enjoys an enormous community, and users can pick and choose from a vast array of third-party libraries to complement its core features.

  • Angular: Boasts a comprehensive ecosystem that's well-managed by its developers and is known for its enterprise support.

  • Vue.js: While the newest of these frameworks, it has been growing rapidly, with a dedicated team and a flourishing community.

Performance

  • React: Focuses on efficient rendering and offers built-in tools for performance optimization.

  • Angular: Optimizes performance through features like Ahead-Of-Time (AOT) compilation and Zone.js, which prevents unnecessary digest cycles.

  • Vue.js: Also optimized for performance, with a small bundle size and features like lazy-loading components.

3. How do you create a component in React?

Creating a React component involves defining its structure, behavior, and sometimes lifecycle methods for dynamic updates. Components can be functional or class-based.

Code Example

`Here's a Class-based component:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}
And here's a Functional one:

import React from 'react';`

const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
Enter fullscreen mode Exit fullscreen mode

Both examples showcase a basic greeting component that takes in a prop name and displays a greeting message.

Linters and JSX
Many modern text editors and IDEs support JSX and JavaScript syntax, especially when integrated with linters like ESLint. This setup provides real-time feedback on errors and formatting issues.

Code Styling with AirBNB and Prettier
It's common to see code bases following the Airbnb style guide, often coupled with Prettier for consistent and automated code formatting.

In the context of component creation, these standards can dictate whether to use single or double quotes for JSX attributes and the method for defining components.

Key Takeaways
JSX offers a natural, HTML-like syntax for building components in React.
Components can be function-based or class-based.
Use modern editing tools and linters for improved code consistency and spotting potential issues in real-time.

4. Functional vs Class-Based Components

Here is the React code:
// Functional Component with useState hook
import React, { useState } from 'react';

export default function Button() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}


// Class-based Component


import React, { Component } from 'react';

export default class Button extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Clicked {this.state.count} times
      </button>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Can you explain the virtual DOM in React?

The Virtual DOM is a key concept in React, responsible for its high performance. It efficiently manages the DOM setup, minimizes updates, and then syncs them to the actual DOM tree.

How the Virtual DOM Works

Initial Rendering: When the application starts, React creates a simplified in-memory representation of the DOM, called the Virtual DOM.

Tree Comparison: During each state change, React builds a new Virtual DOM representation. It then compares this updated representation against the previous one to identify what has changed. This process is often called "reconciliation".

Selective Rendering: React determines the most minimal set of changes needed to keep the Virtual DOM in sync with the actual DOM. This approach, known as "reconciliation", is a performance booster as it reduces unnecessary updates.

Batched Updates: React performs the actual DOM updates in a batch, typically during the next animation frame or when no more updates are being made. This batching leads to optimized DOM operations, further enhancing performance.

One-Way Sync: After the in-memory Virtual DOM and the actual DOM have been reconciled and the necessary updates identified, React syncs these changes in a one-way process, from the Virtual DOM to the actual DOM. This approach helps prevent unnecessary visual glitches and performance hits.

Asynchronous Handling: React schedules state changes, ensuring performance by bundling multiple changes that can be processed together. This aids in avoiding unnecessary Virtual DOM updates and ensures efficient tree comparisons.

Preventing Direct DOM Manipulation: React applications typically avoid manual DOM manipulation. Instead, all changes are made through React, which then uses its Virtual DOM mechanism to batch and apply these changes to the actual DOM.

Support for Cross-Platform Environments: The Virtual DOM gives sturdy cross-platform capabilities, enabling consistent and optimized performance irrespective of the underlying operating system or hardware.

6. What are props and state in React? Explain React state and props

The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.

The main purpose of props is to provide different component functionalities such as:

Passing custom data to the React component.
Using through this.props.reactProp inside render() method of the component.
Triggering state changes.
For example, consider we are creating an element with reactProp property as given below:
This reactProp name will be considered as a property attached to the native props object of React which already exists on each component created with the help of React library: props.reactProp;.

Props

  • Immutable
  • Has better performance
  • Can be passed to child components

State

  • Owned by its component
  • Locally scoped
  • Writeable/Mutable
  • has setState() method to modify properties
  • Changes to state can be asynchronous
  • can only be passed as props

How to declare a state object?

Example:

class Car extends React.Component{
constructor(props){
  super(props);
  this.state = {
    brand: "BMW",
    color: "black"
  }
}
}
Enter fullscreen mode Exit fullscreen mode

How to use and update the state object?


class Car extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    brand: "BMW",
    color: "Black"
  };
}
changeColor() {
  this.setState(prevState => {
    return { color: "Red" };
  });
}
render() {
  return (
    <div>
      <button onClick={() => this.changeColor()}>Change Color</button>
      <p>{this.state.color}</p>
    </div>
  );
}
}
Enter fullscreen mode Exit fullscreen mode

As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property using setState method.

React Props

Every React component accepts a single object argument called props (which stands for “properties”). These props can be passed to a component using HTML attributes and the component accepts these props as an argument.

Using props, we can pass data from one component to another.

Passing props to a component:

While rendering a component, we can pass the props as an HTML attribute:

<Car brand="Mercedes"/>
The component receives the props:

In Class component:

class Car extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    brand: this.props.brand,
    color: "Black"
  };
}
}
In Functional component:

function Car(props) {
let [brand, setBrand] = useState(props.brand);
}
Enter fullscreen mode Exit fullscreen mode

What Is ‘State’ in ReactJS?

The state is a built-in React object that is used to contain data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders. The change in state can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render.

React State

A state can be modified based on user action or network changes
Every time the state of an object changes, React re-renders the component to the browser

The state object is initialized in the constructor
The state object can store multiple properties
this.setState() is used to change the value of the state object
setState() function performs a shallow merge between the new and the previous state

The setState() Method
State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.

Always use the setState() method to change the state object, since it will ensure that the component knows it’s been updated and calls the render() method

class Greetings extends React.Component {
  state = {
    name: "World"
  };

  updateName() {
    this.setState({ name: "Simplilearn" });
  }

  render() {
      return(
          <div>
              {this.state.name}
          </div>
      )
  }
}
Enter fullscreen mode Exit fullscreen mode

7. Explain the lifecycle methods of components

A React Component can go through four stages of its life as follows.

Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.

Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.

Updating: Updating is the stage when the state of a component is updated and the application is repainted.

Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.

8. What is prop drilling in React?

Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.

The disadvantage of using prop drilling is that the components that should otherwise be not aware of the data have access to the data

9. How do you handle events in React?

React simplifies the process of managing and handling events through its use of synthetic events.

Handling Events in React
Synthetic Events
React abstracts browser events into what are known as synthetic events. This ensures a consistent interface across different browsers.

Event Subscription
When handling events, React behaves consistently across all elements, not just form elements.

React events use camelCase, unlike HTML, which is helpful for both consistency and avoiding reserved words in JavaScript.

Use boolean attributes in JSX for default browser events.

Special Event Handling
React provides special interfaces for certain types of events: input components benefit from the value attribute, while media components make use of src or other similar attributes specific to their type.

Code Example: Event Handling
Here is the JavaScript code:

import React from 'react';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

10. What is React Hooks? Explain React Hooks.

React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.

Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState hook, we can keep the state in a functional component.

What are Hooks? Hooks are functions that let us “hook into” React state and lifecycle features from a functional component.

React Hooks cannot be used in class components. They let us write components without class.

Why were Hooks introduced in React?

React hooks were introduced in the 16.8 version of React. Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods. The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of Hooks.

Example of a hook: useState hook:

In functional components, the useState hook lets us define a state for a component:

function Person(props) {
// We are declaring a state variable called name.
// setName is a function to update/change the value of name
let [name, setName] = useState('');
}
Enter fullscreen mode Exit fullscreen mode

The state variable “name” can be directly used inside the HTML.

💖 💪 🙅 🚩
nikhilkalariya
nikhilkalariya

Posted on March 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related