score:275
new answer: much of the below was true, until the introduction of react hooks.
componentdidupdate
can be replicated withuseeffect(fn)
, wherefn
is the function to run upon rerendering.componentdidmount
methods can be replicated withuseeffect(fn, [])
, wherefn
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 withusestate()
, 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 (
<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
score:0
forms are easier with functional, because you can reuse form input fields and you can break them apart with react display conditionals.
classes are one big component that can't be broken down or reused. they are better for function-heavy components, like a component that performs an algorithm in a pop-up module or something.
best practice is reusability with functional components and then use small functional components to assemble complete sections, ex.- form input fields imported into a file for a react form.
another best practice is to not nest components in the process of doing this.
score:2
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.
score:29
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
- state
- lifecycle methods
- memoization with react.purecomponent
functional components:
- state (usestate, usereducer hooks)
- lifecycle methods (via the useeffect, uselayouteffect hooks)
- memoization via the memo hoc
why i prefer funtional components
- react provide the useeffect hook which is a very clear and concise way to combine the
componentdidmount
,componentdidupdate
andcomponentwillunmount
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).
score:46
always try to use stateless functions (functional components) whenever possible. there are scenarios where you'll need to use a regular react class:
- the component needs to maintain state
- the component is re-rendering too much and you need to control that via
shouldcomponentupdate
- you need a container component
update
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
score:60
update march 2019
building on what was stated in my original answer:
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/
update feb 2019:
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.
original answer
functional components aren't any more lightweight than class based components, "they perform exactly as classes." - https://github.com/facebook/react/issues/5677#issuecomment-241190513
the above link is a little dated, but react 16.7.0's documentation says that functional and class components:
are equivalent from react’s point of view
https://reactjs.org/docs/components-and-props.html#stateless-functions
there is essentially no difference between a functional component and a class component that just implements the render method, other than the syntax.
in the future (quoting the above link):
we [react] might add such optimizations
if you're trying to boost performance by eliminating unnecessary renders, both approaches provide support. memo
for functional components and purecomponent
for classes.
-https://reactjs.org/docs/react-api.html#reactmemo
-https://reactjs.org/docs/react-api.html#reactpurecomponent
it's really up to you. if you want less boilerplate, go functional. if you love functional programming and don't like classes, go functional. if you want consistency between all components in your codebase, go with classes. if you're tired of refactoring from functional to class based components when you need something like state
, go with classes.
Source: stackoverflow.com
Related Query
- When to use ES6 class based React components vs. functional ES6 React components?
- Conversion of functional components in react into class based component
- React Class vs Functional Component: When using hooks and functional components one of my functions constantly re-renders
- When using react cdn links for a site does it require the use of class components or can I use function components?
- How to make pure components in react js using functional approach i.e. non class based
- Getting error when I use theme.breakpoints.up in styles for Class Components in React
- Props are empty on passing them to child class based components while filled when using functional component
- React functional stateless component, PureComponent, Component; what are the differences and when should we use what?
- Should we use useCallback in every function handler in React Functional Components
- componentDidMount method not triggered when using inherited ES6 react class
- React hooks: How to write variables in functional components that in class components were initialized in the constructor
- Class based component vs Functional components what is the difference ( Reactjs )
- How to write an ES6 class React Component that extends a functional component?
- How to use redux-toolkit createSlice with React class components
- What is the difference between arrow functions and regular functions inside React functional components (no longer using class components)?
- Cannot call a class as a function, React router show error in console if i use es6 format
- React class components - conditional styling based on props
- Should one use const when declaring an arrow function in React class
- How to convert React class components into functional components and vice versa - IntelliJ
- How to use the updated value in redux store immediately after the action is dispatched in react js functional components
- How to use inheritance with React components and es6 classes
- React component function returning JSX causes error when used in render method of ES6 class React component
- Update child state based on parent state react functional components
- Rewriting React router v4 class based code to v6 functional based
- React - functional components keep re-render when passing functions as props
- use ES6 .map() on multiple times nested objects for react components
- Not able to add, update, delete rows in material table react using class based component. Previously it was working with functional component
- React functional components in Array.map are always rerendering when getting passed a function as props
- How to bundle ES6 based React components and keep the bundle in ES6, using webpack?
- Getting Uncaught TypeError: Cannot call a class as a function when I use a React HOC
More Query from same tag
- Material UI Avatar Image Upload
- flexbox: No space between two vertical icons
- Each child in a list should have a unique "key" prop while rendering all pdf pages with PDF.JS
- MongoDB find vs findOne - find not working
- React: Cannot read property 'times' of undefined Although "times" is defined?
- Navigate through child routes using react-router-dom V6
- × TypeError: Cannot read property 'map' of undefined
- Weird setState behaviour with MaterialUI in React JS
- How to ensure JWT validation occurs before React/Redux router redirect?
- Using query arguments with operators for collections
- chartjs doesn't render dates properly
- My Google Maps is not taking my footer CSS
- how to fetch a string from a string in JS/ReactJs
- Generate RTL CSS file in create-react-app and switch between them based on change in state
- Building an AppBar in React-Toolbox
- Function in React fires but it's not being called
- Drop up for tags input
- Dynamic nested object prop validation - react
- How do I chain actions with Redux Promise Middleware?
- Local GET request different from Heroku deployed request
- Is there a function in ReactJS to wait for a Redux Action to be complete before loading anything in a class?
- Destructuring an object with useState
- How can I change mapStateToProps to use explicit return
- Accessing props in stateless child component (React js + Spring Security)
- React : Template Style property is not update by setState
- I am getting initialization error in the following react-redux code
- How to get all checkbox IDs that are checked using Javascript?
- How to set Material-UI MenuItem width?
- How to export const to other components react?
- Material UI select multiple dates with Calendar