JavaScript
React Components: Class vs Function

by Lipis

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

I would like to know what are the reasons for using functions over classes.

Michael

Around ~3:10: https://egghead.io/lessons/javascript-redux-extracting-presentational-components-addtodo-footer-filterlink

Lipis

@Michael: The quick answer: React will introduce perf improvements for stateless functional components in the future.

The longer answer: Apart from the above, there's no reason to use a class if you're not planning on having local state or the component's context (this) or lifecycle methods. Less boilerplate overall and less typing. Improved readability, especially with ES6 destructuring which makes SFC a joy to write and read:


// silly example

const Button = ({ className, type, children, ...rest }) =>

  <button

    className={className}

    type={type}

    {...rest}

  >

    {children}

  </button>;

SFC encourages microcomponentization and makes your components React-agnostic, any library that implements JSX can use them.

Hope this helps.

Vassilis Mastorostergios

@Vassilis Mastorostergios thx for the explanation

Michael

Why not both? Some should be functional components while others are class components.

Christian Cho

You know, with something like recompose, you can add lifecycle hooks and state to functional components, so actually you don't need to write your own class boilerplate. It obviously still happens under the hood, but it keeps your components consistent.

Chris Cooney

Sign in to comment!