DEV Community

loading...

Discussion on: Learning React? Start Small.

dceddia profile image
Dave Ceddia Author

Ahh I see what you mean.

It's a little confusing because there are 3 different ways to write React components:

  • with React.createClass
  • with ES6 classes (as in your example)
  • with plain functions, either as arrow functions or long-form functions (const MyThing = () => <div>whatever</div> or function MyThing() { return <div>whatever</div> }.

The first one, React.createClass, is deprecated. Old news.

Between the other two, most advice recommends that if the component is stateless, to write it as a function instead of a class. (Scott's example should say "const" instead of "class" but the rest is fine)

Stateless functional components are just as "real" as class components. They're a little more lightweight to write, and they signal the intent of being stateless. They also can't use lifecycle methods. For simple things like Buttons, Headers, etc, they're a great choice.

ES6 class components are best when you know you need to keep track of state, and/or you need to respond to lifecycle methods like componentWillReceiveProps and such. They're also very simple to make "pure", by extending React.PureComponent instead of React.Component.

You can have the best of both worlds (less to type AND things like lifecycle methods) by using the recomponse library, though I still generally prefer to turn things into ES6 classes once they need to do more than just "be pure".