react/prefer-stateless-function

Require class components that only render from props to be functions

A class that has nothing but a render method that reads this.props does the same thing as a function that takes props, with more code around it.

A class that needs to be a class isn't reported. That means a class that:

  • reads anything on this other than props and context, such as this.state
  • has a method or a field other than render, propTypes, defaultProps, contextTypes, and displayName
  • has a constructor that does more than pass its arguments to super
  • has a ref attribute in its JSX
  • has a decorator

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"react/prefer-stateless-function" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"react/prefer-stateless-function" = ["error", {
  ignorePureComponents = false,
}]

Examples#

Reported:

class Greeting extends React.Component {
  render() {
    return <h1>Hello {this.props.name}</h1>;
  }
}

Not reported:

function Greeting(props) {
  return <h1>Hello {props.name}</h1>;
}

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

Options#

OptionDefaultWhat it does
ignorePureComponentsfalseAllow classes that extend PureComponent, which skips a render when the props are the same.

Reported by default:

class Avatar extends React.PureComponent {
  render() {
    return <img src={this.props.url} alt={this.props.name} />;
  }
}

Not reported with ignorePureComponents: true:

class Avatar extends React.PureComponent {
  render() {
    return <img src={this.props.url} alt={this.props.name} />;
  }
}