Skip to content

Favor stateless functions over classes when there's no state #688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 21, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
## Table of Contents

1. [Basic Rules](#basic-rules)
1. [Class vs `React.createClass`](#class-vs-reactcreateclass)
1. [Class vs `React.createClass` vs stateless](#class-vs-reactcreateclass-vs-stateless)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's unfortunate that this will break the link - however since the title on line 28 didn't change, are you sure this link works now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now it works :D

1. [Naming](#naming)
1. [Declaration](#declaration)
1. [Alignment](#alignment)
Expand All @@ -25,27 +25,46 @@
- Always use JSX syntax.
- Do not use `React.createElement` unless you're initializing the app from a file that is not JSX.

## Class vs `React.createClass`
## Class vs `React.createClass` vs stateless

- Use `class extends React.Component` unless you have a very good reason to use mixins.
- If you have internal state and/or refs, prefer `class extends React.Component` over `React.createClass` unless you have a very good reason to use mixins.

eslint rules: [`react/prefer-es6-class`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md).

```javascript
// bad
const Listing = React.createClass({
// ...
render() {
return <div />;
return <div>{this.state.hello}</div>;
}
});

// good
class Listing extends React.Component {
// ...
render() {
return <div />;
return <div>{this.state.hello}</div>;
}
}
```

And if you don't have state or refs, prefer functions over classes:

```javascript

// bad
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}

// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
```

## Naming

Expand Down