DEV Community

loading...

Discussion on: Learning React? Start Small.

Collapse
dceddia profile image
Dave Ceddia Author

Sure, that seems like a good idea. What do you mean by ES6 app structure, and how does it differ from the advice above?

Collapse
thorstenhirsch profile image
Thorsten Hirsch

Well, actually I don't understand Scott's Hello class. It looks like a mixture of the ES6 version (due to the class syntax) and the old functional react style. Since the class lacks a render function one could argue that it's not a real react component.

I would use the following one instead:

import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
  render() {
    return <div>Hello</div>;
  }
}

ReactDOM.render(<Hello/>, document.querySelector('#root'));

Now class Hello is a React.Component and has a render function. It's similar to what the official react tutorial teaches.

Thread Thread
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".