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
thisother thanpropsandcontext, such asthis.state - has a method or a field other than
render,propTypes,defaultProps,contextTypes, anddisplayName - has a constructor that does more than pass its arguments to
super - has a
refattribute 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#
example.jsx1 problem
class Greeting extends React.Component {Component should be written as a pure function
render() {
return <h1>Hello {this.props.name}</h1>;
}
}example.jsxNo problems
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#
| Option | Default | What it does |
|---|---|---|
ignorePureComponents | false | Allow classes that extend PureComponent, which skips a render when the props are the same. |
Reported by default:
example.jsx1 problem
class Avatar extends React.PureComponent {Component should be written as a pure function
render() {
return <img src={this.props.url} alt={this.props.name} />;
}
}Not reported with ignorePureComponents: true:
example.jsxwith
{ "ignorePureComponents": true }No problemsclass Avatar extends React.PureComponent {
render() {
return <img src={this.props.url} alt={this.props.name} />;
}
}