javascriptreactjsecmascript-6

When to use ES6 class based React components vs. ES6 React function components?


After spending some time learning React I understand the difference between the two main paradigms of creating components.

My question is when should I use which one and why? What are the benefits/tradeoffs of one over the other?


ES6 classes:

import React, { Component } from 'react';

export class MyComponent extends Component {
  render() {
    return (
      <div></div>
    );
  }
}

Function:

const MyComponent = (props) => {
  return (
    <div></div>
  );
}

I’m thinking function component whenever there is no state to be manipulated by that component, but is that it?

I’m guessing if I use any life cycle methods, it might be best to go with a class based component.


Solution

  • You have the right idea. Go with functional if your component doesn't do much more than take in some props and render. You can think of these as pure functions because they will always render and behave the same, given the same props. Also, they don't care about lifecycle methods or have their own internal state.

    Because they're lightweight, writing these simple components as functional components is pretty standard.

    If your components need more functionality, like keeping state, use classes instead.

    More info: https://facebook.github.io/react/docs/reusable-components.html#es6-classes