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

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

  • componentDidUpdate can be replicated with useEffect(fn), where fn is the function to run upon rerendering.

  • componentDidMount methods can be replicated with useEffect(fn, []), where fn is the function to run upon rerendering, and [] is an array of objects for which the component will rerender, if and only if at least one has changed value since the previous render. As there are none, useEffect() runs once, on first mount.

  • state can be replicated with useState(), whose return value can be destructured to a reference of the state and a function that can set the state (i.e., const [state, setState] = useState(initState)). An example might explain this more clearly:

const Counter = () => {
  const [count, setCount] = useState(0)

  const increment = () => { 
    setCount(count + 1);

  return (
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>

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

Leave a Comment