Eslint-plugin-react: Rule Proposal: always use functional components for pure render component

Created on 5 Mar 2018  路  6Comments  路  Source: yannickcr/eslint-plugin-react

This code should be always

class Something extends Component {
  componentDidMount() {
    someSideEffect()
  }

  render() {
    return (
      <div>
        // Some complex structure
      </div>
    )
  }
}

refactored to this:

const SomethingRenderer = () => (
  <div>
    // Some complex structure
  </div>
)

class Something extends Component {
  componentDidMount() {
    someSideEffect()
  }

  render() {
    return <SomethingRenderer />
  }
}

Proposal

Always extract rendering into separate functional render components. Never mix them with dirty class based components.

Benefits:

  1. Composability of renderers - because they will have no dependencies on hooks/state/instance.
  2. Readability of renderers - data comes from props only, not from state/instance
  3. 0 extra work once you want to reuse renderer somewhere else, just move it to a separate file or export it.
  4. Render components are likely to survive any react api changes, because they only rely on props, function with props returning jsx will never change.

Most helpful comment

Certainly it can be. What I'm trying to suggest is that it's a bad rule because it would be forcing separation that isn't needed to ensure a clean codebase.

All 6 comments

This seems a bit heavy handed; while I agree with the design principle, it's not really reasonable for a rule to ban any non-pure/non-SFC component (note that SFCs aren't necessarily pure by any means) from rendering anything besides a custom component. What about Something's props and children?

@ljharb can you please make an example or something? I am not quite sure what makes it "heavy handed"

@kof specifically, there's about 9,000 React components in airbnb's codebase, and my hunch is that about 7,000 of them would fail this rule. That seems heavy-handed to me.

Sure, it can be optional, right? I mean we both agree it makes sense, no?

Certainly it can be. What I'm trying to suggest is that it's a bad rule because it would be forcing separation that isn't needed to ensure a clean codebase.

I came to understanding that it does, but I understand that not everyone will share my opinion. What matters is if there are enough people who do, so we can add this linting rule.

Was this page helpful?
0 / 5 - 0 ratings