React class vs. functional vs. pure components

August 02, 2018
Class Component
class Header extends Component {
  render() {
    return <Menu items={this.props.items} />
  }
}

Functional Component
const Header = ({ items }) =>
  <Menu items={items} />

When it comes to choosing a class vs. functional component, there’s a simple rule of thumb: if you need state or lifecycle methods, use a class. Otherwise, use a functional component. This is because functional components require less boilerplate, the code is much cleaner, and the core team is eventually going to introduce performance benefits for using them.

There’s a third option if you’re concerned about performance: the pure component. Pure components limit the number of unnecessary re-renders that occur. There are two ways to define pure components:

Pure Component
// Extend your component from PureComponent
class Option1 extends PureComponent {
  render() {
    return <Menu items={this.props.items} />
  }
}

// Or define a custom shouldComponentUpdate method
class Option2 extends Component {
  shouldComponentUpdate() {
    // define custom logic here...
  }

  render() {
    return <Menu items={this.props.items} />
  }
}

Pure components are much more performant than class components, but they come with a few gotchas:

  1. Shallow equality checks. React will only check against memory addresses to rerender your components, which means that if you’re trying to update nested data, your component won’t re-render.
  2. Children re-rendering. None of a pure component’s children will re-render unless the parent re-renders.

Want more?

My newsletter sends rarely. It's where I share updates on the best of my writing: introverted entrepreneurship, esoteric mindset tips, notes from great books, and automating businesses as a solo-owner so they run by themselves. Want to join?

Subscribe