no-class-component
Disallows class components except for error boundaries.
Full Name in eslint-plugin-react-x
react-x/no-class-componentFull Name in @eslint-react/eslint-plugin
@eslint-react/no-class-componentPresets
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
react-x/no-component-will-mount
Replaces usage ofcomponentWillMountwithUNSAFE_componentWillMount.react-x/no-component-will-receive-props
Replaces usage ofcomponentWillReceivePropswithUNSAFE_componentWillReceiveProps.react-x/no-component-will-update
Replaces usage ofcomponentWillUpdatewithUNSAFE_componentWillUpdate.react-x/no-unsafe-component-will-mount
Warns about the use ofUNSAFE_componentWillMountin class components.react-x/no-unsafe-component-will-receive-props
Warns about the use ofUNSAFE_componentWillReceivePropsin class components.react-x/no-unsafe-component-will-update
Warns about the use ofUNSAFE_componentWillUpdatein class components.