Try @eslint-react/kit@beta
logoESLint React

no-class-component

Disallows class components except for error boundaries.

Full Name in eslint-plugin-react-x

react-x/no-class-component

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-class-component

Presets

strict strict-typescript strict-type-checked

Rule Details

Component is the base class for React components defined as JavaScript classes. Class components are still supported by React, but we don't recommend using them in new code.

We recommend defining components as functions instead of classes. See how to migrate.

Examples

Writing a new component

For new code, prefer function components with Hooks. They are simpler, easier to compose, and align with React's current direction.

// Problem: Using a class component for new logic
import React from "react";

interface MyComponentProps {
  name: string;
}

class MyComponent extends React.Component<MyComponentProps> {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}
// Recommended: Use a function component instead
interface MyComponentProps {
  name: string;
}

function MyComponent({ name }: MyComponentProps) {
  return <h1>Hello, {name}!</h1>;
}

Defining an error boundary

Error boundaries must currently be implemented as class components because componentDidCatch and getDerivedStateFromError have no function-component equivalent. This is an allowed exception.

// OK: Error boundaries must be implemented as class components
import React, { Component } from "react";

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

class ErrorBoundary extends Component<ErrorBoundaryProps> {
  state = { hasError: false };

  static getDerivedStateFromError(error: Error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

Versions

Resources

Further Reading


See Also

On this page