Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways of defining ES6 React Components

I was looking at this fiddle for MobX and I've seen these two ways of defining React Components in ES6 other places as well, like Dan Abramov's egghead redux video series.

@observer
class TodoListView extends Component {
    render() {
        return <div>
            <ul>
                {this.props.todoList.todos.map(todo => 
                    <TodoView todo={todo} key={todo.id} />
                )}
            </ul>
            Tasks left: {this.props.todoList.unfinishedTodoCount}
        </div>
    }
}

const TodoView = observer(({todo}) =>
    <li>
        <input
            type="checkbox"
            checked={todo.finished}
            onClick={() => todo.finished = !todo.finished}
        />
        <input
            type="text"
          value={todo.title}
          onChange={ e => todo.title = e.target.value } />
    </li>
);

My question is, when is it appropriate to use each type?

It seems like the simpler components are able to use the simpler syntax, but I'd like a rule or guideline to follow.

Thanks!

like image 738
Grant Eagon Avatar asked Mar 01 '16 14:03

Grant Eagon


1 Answers

The second pattern is called "stateless functional components", and using it is recommended in almost all cases. SFCs (stateless functional components) are pure functions that are only dependent on their props. They are easier to test, decoupled from each other and will have significant performance gains over other patterns in the future. (source from the official react documentation)

They have a few gotchas though, namely:

  • One cannot attach refs to SFCs. (src, src2)
  • They cannot have internal state. (src)
  • They cannot use lifecycle methods. (e.g. componentDidMount, src)

If you need any of these things, first make sure there is no way around using them and only then use either the ES6 class or the React.createClass patterns.


I highly recommend "Should I use React.createClass, ES6 Classes or stateless functional components?" by James K Nelson to understand the tradeoffs and difference between these patterns, and "Presentational and Container Components" by Dan Abramov for an explanation of the most commonly used structure for Redux applications.

like image 82
mxstbr Avatar answered Oct 21 '22 23:10

mxstbr