Class Components in React — React Technical Interview Questions & Answers

Class Components in React

Class Components in React

  • A class component extends React.Component, keeps data in this.state, updates with this.setState, and draws in render(). Lifecycle methods: componentDidMount, componentDidUpdate, componentWillUnmount. You will still read this in older codebases.
  • Map to hooks: state → useState, didMount/didUpdate/willUnmount → useEffect. Don’t start a new screen as a class unless the team’s file already is one. Interview: show you can read a class, then say you’d rewrite it as a function.
  • Class Components in React — on screen: button 0, click → 1. Class uses this.setState. Today we write useState instead.
  Parent
    │ props (read-only)
    ▼
  Child → UI

Technical Interview Tip: Read class. Prefer hooks for new code.

Code Examples for Class Components in React

Example

// Class component
import { Component } from "react";

class Counter extends Component {
  state = { n: 0 };
  render() {
    return (
      <button onClick={() => this.setState({ n: this.state.n + 1 })}>
        {this.state.n}
      </button>
    );
  }
}

Class Components in React — on screen: button 0, click → 1. Class uses this.setState. Today we write useState instead.

How to Explain Class Components in React to an Interviewer

Explain Class Components as if you are teaching a junior — definition, then one tiny UI.

class + this.state + render(). didMount ≈ useEffect([]).

What does the example show on screen (or print), and what does that prove?

Class Components in React — on screen: button 0, click → 1

What mistake do freshers make with Class Components?

function components.