Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

When to Use Class Components vs Function Components

In earlier versions of React (before 2019), Class Components were the primary way to manage component state and lifecycle methods (like componentDidMount, componentDidUpdate, etc.). However, with the introduction of Hooks in React 16.8, Function Components can now handle state, side effects, and more — making them powerful and preferred for most use cases today.

Here’s a detailed comparison:

Class Components

  • When to use:
    • If you are maintaining or updating an older codebase that already uses classes.
    • When you need to use lifecycle methods in a class-based project (componentDidMount, shouldComponentUpdate, etc.).
  • Characteristics:
    • More boilerplate code (constructor, this keyword).
    • Traditionally used for complex logic before Hooks existed.
    • Example:
      class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>Count: {this.state.count}</p> </div> ); } }

Function Components

  • When to use:
    • For all new React development, especially when you need a cleaner, simpler syntax.
    • When you want to use Hooks like useState, useEffect, useContext, etc.
  • Characteristics:
    • Less code, more readable.
    • Capable of managing state and lifecycle with Hooks.
    • Encourages better separation of concerns (custom Hooks for logic).
    • Example:
      import { useState } from 'react'; function MyComponent() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> </div> ); }

Summary

  • Use Function Components for new development.
  • Use Class Components mainly when working with existing code that already uses classes.
  • Thanks to Hooks, function components are now equally powerful, more concise, and easier to test and maintain.

🔥 Pro Tip: Companies moving towards modern React development prefer candidates familiar with Hooks and functional components.