mediumFrontend

When would you choose a class component over a functional component with hooks?

610 views
01

Understand the problem

Although functional components with hooks are preferred, identify scenarios where a class component might still be necessary or advantageous.

class componentsfunctional componentshookslegacy
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

The one class you still write: an Error Boundary
import { Component } from "react";

class ErrorBoundary extends Component {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  componentDidCatch(error, info) { console.error(error, info); }
  render() {
    return this.state.hasError ? <p>Something went wrong.</p> : this.props.children;
  }
}

function Boom() { throw new Error("render error"); }

export default function App() {
  return (
    <div style={{ padding: 24, fontFamily: "system-ui" }}>
      <ErrorBoundary><Boom /></ErrorBoundary>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.