404

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.

4
  • 5
    If you have a component with render method only, you can turn it into functional form. If you need something more than stateless render function, use classes Commented Mar 20, 2016 at 19:02
  • 2
    To be even more concise try this: const MyComponent = (props) => <div>...</div> Commented Aug 15, 2017 at 10:57
  • IMHO, React job is knowing when to rerender bits of UI, and rerender when necessary. To make this decision, React needs to know if component state has changed and if this change should trigger a rerender. Check for changes in complex objects is a difficult task. Using immutable objects makes it easier (just an address change check) for React. Immutability is part of functional programming. So, from what I understand, functional components makes it easier for React folks to make React good at what it has to do : render a UI when necessary. UI is a function of state after all. Commented Mar 10, 2020 at 17:56
  • Top answer is outdated since hooks are a thing. Another Q&A seems like a newer version of this one, though one answer below actually covers hooks: stackoverflow.com/a/55814976 Commented Aug 15 at 14:49

7 Answers 7

315

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

Sign up to request clarification or add additional context in comments.

8 Comments

As of React 16.8, you can use state in a functional component, via the useState hook.
Where have you find the info where Facebook officially recommends using functional components wherever possible?
I'm also curious about the Facebook officially recommends using functional components wherever possible.
Seems FB's recommendation has changed over time: In 2016-June, they recommended functional components, in 2016-Oct they recommended functional components when you don't need state, ES6 classes when you do and in 2016-Nov, their recommendation was removed altogether.
I've rolled back to the user's original answer. @NickBull please note that massive rewrites of someone else's answer are not allowed on Stack Overflow unless the post is Community Wiki. If you have a new or different answer, post it as a separate answer; don't edit someone else's.
|
87

TL;DR Functions are the best way to create components. React.Component is a legacy API.

We recommend defining components as functions instead of classes.

Class components are still supported by React, but we don’t recommend using them in new code.

https://react.dev/reference/react/Component

Are there any fundamental differences between React functions and classes at all? Of course, there are — in the mental model.

https://overreacted.io/how-are-function-components-different-from-classes/

With the introduction of React hooks, it seems as though the React teams wants us to use functional components whenever possible (which better follows JavaScript's functional nature).

Their motivation:

  1. It’s hard to reuse stateful logic between components.
  2. Complex components become hard to understand.
  3. Classes confuse both people and machines.

A functional component with hooks can do almost everything a class component can do, without any of the draw backs mentions above.

I recommend using them as soon as you are able.

5 Comments

I think making every component extend React.Component makes the code more readable, especially for the new people. It is nice when you see a component created the same way every time. Like @Galupuf said, simple components just have one method called "render()". It is also nice to make everything extend React.Component because when you want to start binding "this", having state, etc. you don't have to refactor everything, you can just add what you need.
points 2 and 3 are as redundant as they are unfounded.
@jeffski13 so you are in favor of Class based react components? Or functional components?
Maybe there is something I am missing. However it seems like if your problem at hand would benefit from a class structure then it might be a good idea to go with a class. For example if you think inheritance would be nice to have, then go with a class. If you want to be able to unit test the separate functions of a class then go with a class. I feel like most of the time it makes sense to go functional but sometimes having a class can be preferable.
componentDidMount and componentDidUpdate are much clearer names then "useEffect" with or without an empty dependency
48

There's now a React class called PureComponent that you can extend (instead of Component) which implements its own shouldComponentUpdate that takes care of shallow props comparison for you. Read more

7 Comments

Always try to use stateless functions (functional components) whenever possible. I have read ten people say that. Still none of them gave an explanation why.
In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible. More info: facebook.github.io/react/docs/…
@rotareti I don't know if you feel you got your question answered, but pure functions are much simpler to understand, test and maintain. Given the same parameters, they always render the same thing. Components that maintain state and change when lifecycle events occur are harder to understand. Not to say they aren't sometimes needed, but I hope it's clear that if their advantages are not needed, all they do is add unwanted boilerplate and overhead with no benefits.
You will also want to create a Component class if you have your own event handler definitions. That way you can pre-bind those event handlers to the component in the constructor instead of creating a fresh new function on every render. Note this is not needed if all your event handlers come from props.
@rotareti, I can see the benefit of functional components (memoization), but from my personal encounters and experiences, I think functional components are much HARDER to reason about. I think people think all functional components will be written with just a few lines of code but many times I have found MASSIVE functional components doing way too many things at once; functions and event handlers everywhere; code is unreadable! Such code should be written in an object oriented way: either the component needs to be class-based or all those handlers need to be written as a class service.
|
33

As of React 17 the term Stateless Functional components is misleading and should be avoided (React.SFC deprecated, Dan Abramov on React.SFC), they can have a state, they can have hooks (that act as the lifecycle methods) as well, they more or less overlap with class components

Class based components

Functional components:

Why i prefer Funtional components

  • React provide the useEffect hook which is a very clear and concise way to combine the componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods
  • With hooks you can extract logic that can be easily shared across components and testable
  • less confusion about the scoping

React motivation on why using hooks (i.e. functional components).

Comments

3

I have used functional components for heavily used application which is in production. There is only one time I used class components for "Error Boundaries" because there is no alternative "Error Boundaries" in functional components.

I used "class component" literally only one time.

1 Comment

FWIW, there is an npm package for error boundaries: npmjs.com/package/react-error-boundary. Haven't used it myself, though.
1

Class-based components offer a more structured and organized way to define and implement a component, and they provide additional features and capabilities, such as the ability to use local state and lifecycle methods. This can make them a good choice for creating complex components that require a lot of logic and functionality.

On the other hand, functional components are simpler and easier to work with, and they can be more performant because they are more lightweight. They are also easier to test and debug, because they are pure functions that don't have side effects. This makes them a good choice for creating simple components that don't require a lot of logic or state management.

1 Comment

Class-based components offer a more structured and organized way... I don't think this is correct.
0

I think using functional method as it can.

We recommend defining components as functions instead of classes. See how to migrate.

read more(React dev document)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.