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!
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:
ref
s to SFCs. (src, src2)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With