React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 37

What is the difference between class components and functional components with hooks?

Answer:

React provides two main types of components: class components and functional components with hooks. Here’s a detailed comparison between the two:

Class Components

Class components are ES6 classes that extend React.Component and have access to lifecycle methods and state management via this.state and this.setState.

Example:

import React, { Component } from 'react';

class MyClassComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default MyClassComponent;

Characteristics:

  1. State Management: State is managed via this.state and updated using this.setState.
  2. Lifecycle Methods: Access to lifecycle methods such as componentDidMount, shouldComponentUpdate, componentDidUpdate, etc.
  3. this Keyword: Requires proper binding of this in methods (often handled using arrow functions or bind in the constructor).
  4. Boilerplate Code: Typically more boilerplate code compared to functional components with hooks.

Functional Components with Hooks

Functional components are simpler JavaScript functions that return JSX. With the introduction of hooks in React 16.8, functional components can manage state and side effects.

Example:

import React, { useState } from 'react';

function MyFunctionalComponent() {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

export default MyFunctionalComponent;

Characteristics:

  1. State Management: State is managed using the useState hook.
  2. Side Effects: Side effects and lifecycle management are handled using the useEffect hook.
  3. Simpler Syntax: Generally simpler and more concise syntax compared to class components.
  4. No this Binding: No need to bind this since there is no this context in functional components.
  5. Hooks: Provides powerful hooks like useState, useEffect, useContext, useReducer, useCallback, useMemo, etc., for managing state, side effects, context, reducers, and memoization.

Key Differences

  1. State and Lifecycle Management:

    • Class Components: Use this.state for state management and lifecycle methods (componentDidMount, componentDidUpdate, etc.) for side effects.
    • Functional Components with Hooks: Use hooks like useState for state management and useEffect for side effects.
  2. Syntax and Readability:

    • Class Components: Typically more verbose due to the need for class syntax, constructor, and this bindings.
    • Functional Components with Hooks: More concise and readable, leveraging simple function syntax.
  3. Performance:

    • Class Components: May have slightly more overhead due to the ES6 class and method bindings.
    • Functional Components with Hooks: Potentially more performant and easier to optimize with hooks like useMemo and useCallback.
  4. this Context:

    • Class Components: Require careful handling of this context, often leading to the use of arrow functions or manual binding.
    • Functional Components with Hooks: No this context, which simplifies the component logic.
  5. Development Speed:

    • Class Components: Can be slower to write and maintain due to boilerplate code and lifecycle method complexity.
    • Functional Components with Hooks: Faster development with less boilerplate and more intuitive handling of state and side effects.
  6. Community and Ecosystem:

    • Class Components: Historically the standard way to write components, so older codebases and some libraries may still use them.
    • Functional Components with Hooks: The preferred approach in modern React development, with growing community support and new libraries designed to leverage hooks.

Migration from Class to Functional Components

Many developers and teams are migrating from class components to functional components with hooks due to the simpler syntax and powerful features provided by hooks. The transition can often lead to more maintainable and efficient codebases.

Conclusion

Both class components and functional components with hooks have their use cases, but functional components with hooks are now the preferred approach in modern React development due to their simplicity, improved performance, and the powerful features provided by hooks. Understanding the differences and when to use each can help developers make informed decisions and write better React applications.

Recent job openings