javascriptreactjsecmascript-6redux

When to use ES6 class based React components vs. functional ES6 React 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>
    );
  }
}

Functional:

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

I’m thinking functional 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

  • New Answer: Much of the below was true, until the introduction of React Hooks.

    const Counter = () => {
      const [count, setCount] = useState(0)
    
      const increment = () => { 
        setCount(count + 1);
      }
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={increment}>+</button>
        </div>
      )
    }
    
    default export Counter
    

    As a small aside, I have heard a number of people discussing not using functional components for the performance reasons, specifically that

    "Event handling functions are redefined per render in functional components"

    Whilst true, please consider if your components are really rendering at such a speed or volume that this would be worth concern.

    If they are, you can prevent redefining functions using useCallback and useMemo hooks. However, bear in mind that this may make your code (microscopically) worse in performance.

    But honestly, I have never heard of redefining functions being a bottleneck in React apps. Premature optimisations are the root of all evil - worry about this when it's a problem.


    Old Answer: 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