15

In react tutorial:

https://egghead.io/lessons/javascript-redux-react-todo-list-example-filtering-todos

there is main component create with extends:

class TodoApp extends Component {
  render() {
    const visibleTodos = getVisibleTodos(
      this.props.todos,
      this.props.visibilityFilter
    );
    .
    . // Input and Button stuff
    .

and another components just create like a const that hold a function:

const FilterLink = ({
  filter,
  children
}) => {
  return (
    <a href='#'
       onClick={e => {
         e.preventDefault();
         store.dispatch({
           type: 'SET_VISIBILITY_FILTER',
           filter
         });
       }}
    >
      {children}
    </a>
  )
}

the difference i see, first created with class use a render function, and the another a return function to send back the template.

What are the differences? I've heard components in the future only will be allowed with extend Component ?

stackdave
  • 6,655
  • 9
  • 37
  • 56
  • You want to read about [stateless components](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions). – moonwave99 Sep 20 '16 at 10:09
  • thanks i've just read: 'These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods' but it's not yet clear for me when to choose it – stackdave Sep 20 '16 at 10:16
  • I guess the general idea is to go for the simpler stateless option when you don't need all of the extra stuff. – Tom Fenech Sep 20 '16 at 10:19

2 Answers2

25

See: React.createClass vs. ES6 arrow function

The short answer is that you want to use Stateless Functional Components (SFC) as often as you can; the majority of your components should be SFC's.

Use the traditional Component class when:

  • You need local state (this.setState)
  • You need a lifecycle hook (componentWillMount, componentDidUpdate, etc)
  • You need to access backing instances via refs (eg. <div ref={elem => this.elem = elem}>)
Community
  • 1
  • 1
Joshua Comeau
  • 2,594
  • 24
  • 25
1

class Foo extends Component {} results in components with some React lifecycle hooks, while const Foo = (props) => {} does not. The latter should therefore result in more performant code and would be considered a "stateless" or "pure" component, as it doesn't come with any additional baggage.

Louis Moore
  • 607
  • 6
  • 6