ReactJS: what is the difference between functional component and class component - javascript

Could anyone can explain in detail the difference between functional component and class component in ReactJS?
When we use a functional component and when we use the class component?

Here's a great article, "Presentational and Container Components", by Dan Abramov that can help you with that.
And here's a tl;dr; of the way I understand this:
You'll have to use class CreatePostForm extends Component {} or React.createClass() if:
you need access to your component's lifecycle methods (ie.: componentWillMount or componentDidMount) – NOTE: Since React 16.8, this is no longer necessarily true and I would highly recommend reading on React Hooks as they can make things simpler once you get comfortable with them;
your component have direct access to your store and thus holds state (some people also call these components: smart components or containers).
When your component just receive props and render them to the page, then you have a 'stateless component' (some people call these components dumb components or presentational components) and can use a pure function to represent it and it can be as simple as this
import React from 'react';
export default () => <p>Hello from React!</p>;
Now, it's important to remember that a pure function can get way more complex than this and if you're comfortable with some ESNext syntax and destructuring and spreading attributes, you can have a presentational component that looks like this:
import React from 'react';
import AnotherComponent from './AnotherComponent';
export default ({ children, ...rest }) =>
<AnotherComponent extraProp="anExtraProp" { ...rest }>
{ children }
</AnotherComponent>;
Hope this helps.

See this picture. I am too much late but i will help the others.
Source of Image is Udemy Course

Functional Stateless Components (that middle word you missed is the important one) are just a 'dumb' function that takes props as an input and outputs markup. They don't have any state or methods or anything like that. Just (props) => { return <span>props.foo</span>; }
Class components can have state, variables, methods etc.

Functional Components:
These components are stateless components and does not have react life-cycle methods.
These components can be used for presentation purpose.
These components can be easy to debug,test.
Class Components:
These components are statefull components and can support react life-cycle methods by extending react components.
These components can be used when you want to create methods , state for an component.

Functional Components
A functional component is basically a JavaScript function which returns a React element. Its accepts props as argument and returns valid JSX
Class Components
Class Components are more complex than functional components including constructors, life-cycle methods, render( ) function and state (data) management. Class components are ES6 classes.
Benefits of using Functional Components
Functional components are easy to test.
It can have better performance.
Functional components are easy to debug.
It end up with less code.
It help you to use best practices.
Functional components can reduce coupling.
For more click here

When react was introduced, only class components were used to re-render the component when state changes and functional components were treated as presentational components as they don't have state access.
From react 16.8 version update, with introduction to hooks, now functional components also have state access.
In the class component, managing state is performed in a single state object but in function we can create as many hooks as we want.
In the class component, when re-render happens, it will invoke methods but in functional components when state update, it re-create and invoke inner functions if we don't use useCallback and useMemo hooks.
Only Class components are used as Error Boundaries

Functional Component : Using simple javascript function to define component.
it uses props as input(stateless)
Class Component : Using class to define a component(state Component)

Besides the obvious difference in the syntax, you need use a class component instead of a function component when your component needs to store and manipulate its own internal state or when you need access to the several lifecycle methods like componentDidMount, etc to perform network operations, manipulate the DOM, interact with third-party libraries, etc
I recommend you to take a look a the React docs (https://reactjs.org/docs/react-component.html) about the React.Component API to find a detailed description of all the lifecycle methods and the state API.

1-Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
2-You end up with less code
3-They help you to use best practices. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component
4-The React team mentioned that there may be a performance boost for functional component in future React versions

In the world of react, there are two ways to write components:-
Using functions
Using class
The following example shows the two ways you can write the same component.
Functional component
import React from "react";
function FunctionalComponent() {
return <h1>Hello, world</h1>;
}
Class component
import React, { Component } from "react";
class ClassComponent extends Component {
render() {
return <h1>Hello, world</h1>;
}
}
With Recent releases of React, the choice of when to write when depends on the developer's preferences.
Both styles have their own pros and cons. Functional components are taking over modern React in the foreseeable future. Everything we can do with class components is possible with the functional components. It can be written shorter and simpler, which makes it easier to develop, understand, and test.
React team is supporting more React hooks for functional components that replace or even improve upon class components. They mentioned in prior releases that they will make performance optimizations in functional components by avoiding unnecessary checks and memory allocations. And as promising as it sounds, new hooks are recently introduced for functional components such as useState or useEffect while also promising that they are not going to obsolete class components but recommend a gradual adoption strategy.

Function component is a Hook Using work and the usestate and any other hook function to use and dynamic data display then some problem for function component in a reactjs
Class Component is an easy way to use for compare to function component and daynamic data update then to easily work. Class component is what state and props use to pass runtime data to a component.

Related

Rendering query string variables in React [duplicate]

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.
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 (
<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
UPDATE Jan 2023
TLDR; Functions are the best way to create components. React.Component is a legacy API.
"We recommend to define components as functions instead of classes."
"Class components are still supported by React, but we don’t recommend using them in new code."
https://beta.reactjs.org/reference/react/Component
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:
It’s hard to reuse stateful logic between components.
Complex components become hard to understand.
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.
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
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 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).
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.
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.
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.

When to use class-based component in React

After React Hooks were introduced in React 16.8 with all the new ways to control component's state and lifecycle methods in a functional component such as useState and useEffect, the remaining difference between a functional component and a class-based component isn't obvious anymore, so what's the real difference ?
There are some lifecycle methods, which can't be emulated with React Hooks(e.g. componentDidCatch()).
In this cases you still need class components, but overall, you don't need them, and it's already totally fine, if you have an app without them.

React Multiple Higher-Order Components

I'm just discovering the amazing benefits of using HOC in my react projects.
My question is there any performance hit for calling multiple HOC functions on a component?
Example
export default withState(withLabel(withTheme(MyComponent)))
This will of course only render one component, however looking at my react dev tools i can see the outputted HOC components three levels deep. Is this something to be wary of or is there a better approach to calling multiple HOC on a component?
Your syntax is equivalent to doing:
<StateProvider>
<LabelProvider>
<ThemeProvider>
<MyComponent />
</ThemeProvider>
</LabelProvider>
</StateProvider>
The performance hit will come from how these HOC are implemented. You would probably have to look at each of them.
Example:
Theme Provider HOCs usually store a bunch of colors and variables in the React context. So using only one at the very root of your App is enough.
One could imagine that your LabelProvider simply adds an extra span before your component, in which case there is little to worry about
StateProviders like redux usually inject props in the component just below them so you don't really have a choice but to use them whenever you need state objects.
In conclusion, there are no hard rules. Your main focus should be on understanding what these HOC do and to try to limit unnecessary re-renders of your app.
I wouldn't use that. It's complicated to understand where the props come from, when you are looking at your MyComponent component. There are much more downsides using this pattern. Anyway if you decided to use HOCs use it in a right way e.g.
const withDetails = Component => {
const C = props => {
// do something
}
// assign display & wrapped names - easier to debug
C.displayName = `withRouter(${Component.displayName))`
C.WrappedComponent = Component;
return C;
}
Instead of using HOCs i suggest looking at render props react pattern. It's well explained in a Use a Render Prop! article by Michael Jackson (react-router creator).
Hope it makes sense.

React & Redux - container component inside a presentational component?

I know this might be a little opinion-based question, but I think an important one.
In short, is it good practice to have react container components inside a react presentational component? What would you say could be the benefits and disadvantages of this practice of having container components inside a react presentational component?
I think that presentational components should be dummy: They take in props, and behave according to them, and nothing else affects them. They behave expectedly when given certain props, and nothing outwhere should affect their behaviour.
What could be the problem then having container component(s) inside a presentational component? Well, as container components usually have access to the (global) store (in redux), you cannot know simply from the props of the presentational component, that how the component will behave. Because the store will affect to the behaviour of the container component, and as it is included in the presentational component, then the presentational component is no longer a dummy component. What do you think?
I assume that by presentational component you are referring to a ReactJS functional component?
If so, I do not see a problem with this approach. The resulting component wouldn't be purely presentational, but it would do the job of defining the composition of the component(s) it renders.
Depending on the context, this could be exactly regards you need.
Rather than trying to build an application starting with presentational components, I prefer to take the approach of first scaffolding the bulk of my application and then refactor what I need to into presentational components.

React functional stateless component, PureComponent, Component; what are the differences and when should we use what?

Came to know that from React v15.3.0, we have a new base class called PureComponent to extend with PureRenderMixin built-in. What I understand is that, under the hood this employs a shallow comparison of props inside shouldComponentUpdate.
Now we have 3 ways to define a React component:
Functional stateless component which doesn't extend any class
A component that extends PureComponent class
A normal component that extends Component class
Some time back we used to call stateless components as Pure Components, or even Dumb Components. Seems like the whole definition of the word "pure" has now changed in React.
Although I understand basic differences between these three, I am still not sure when to choose what. Also what are the performance impacts and trade-offs of each?
Update:
These are the question I expect to get clarified:
Should I choose to define my simple components as functional (for the sake of simplicity) or extend PureComponent class (for performance sake)?
Is the performance boost that I get a real trade-off for the
simplicity I lost?
Would I ever need to extend the normal Component class when I can always use PureComponent for better performance?
How do you decide, how do you choose between these three based on the purpose/size/props/behaviour of our components?
Extending from React.PureComponent or from React.Component with a custom shouldComponentUpdate method have performance implications. Using stateless functional components is an "architectural" choice and doesn't have any performance benefits out of the box (yet).
For simple, presentational-only components that need to be easily reused, prefer stateless functional components. This way you're sure they are decoupled from the actual app logic, that they are dead-easy to test and that they don't have unexpected side effects. The exception is if for some reason you have a lot of them or if you really need to optimise their render method (as you can't define shouldComponentUpdate for a stateless functional component).
Extend PureComponent if you know your output depends on simple props/state ("simple" meaning no nested data structures, as PureComponent performs a shallow compare) AND you need/can get some performance improvements.
Extend Component and implement your own shouldComponentUpdate if you need some performance gains by performing custom comparison logic between next/current props and state. For example, you can quickly perform a deep comparison using lodash#isEqual:
class MyComponent extends Component {
shouldComponentUpdate (nextProps, nextState) {
return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState);
}
}
Also, implementing your own shouldComponentUpdate or extending from PureComponent are optimizations, and as usual you should start looking into that only if you have performance issues (avoid premature optimizations).
As a rule of thumb, I always try to do these optimisations after the application is in a working state, with most of the features already implemented. It's a lot easier to focus on performance problems when they actually get in the way.
More details
Functional stateless components:
These are defined just using a function. Since there's no internal state for a stateless component, the output (what's rendered) only depends on the props given as input to this function.
Pros:
Simplest possible way of defining a component in React. If you don't need to manage any state, why bother with classes and inheritance? One of the main differences between a function and a class is that with the function you are sure the output depends only on the input (not on any history of the previous executions).
Ideally in your app you should aim to have as many stateless components as possible, because that normally means you moved your logic outside of the view layer and moved it to something like redux, which means you can test your real logic without having to render anything (much easier to test, more reusable, etc.).
Cons:
No lifecycle methods. You don't have a way to define componentDidMount and other friends. Normally you do that within a parent component higher in the hierarchy so you can turn all the children into stateless ones.
No way to manually control when a re-render is needed, since you can't define shouldComponentUpdate. A re-render happens every time the component receives new props (no way to shallow compare, etc.). In the future, React could automatically optimise stateless components, for now there's some libraries you can use. Since stateless components are just functions, basically it's the classic problem of "function memoization".
Refs are not supported: https://github.com/facebook/react/issues/4936
A component that extends PureComponent class VS A normal component that extends Component class:
React used to have a PureRenderMixin you could attach to a class defined using React.createClass syntax. The mixin would simply define a shouldComponentUpdate performing a shallow comparison between the next props and the next state to check if anything there changed. If nothing changes, then there's no need to perform a re-render.
If you want to use the ES6 syntax, you can't use mixins. So for convenience React introduced a PureComponent class you can inherit from instead of using Component. PureComponent just implements shouldComponentUpdate in the same way of the PureRendererMixin. It's mostly a convenience thing so you don't have to implement it yourself, as a shallow comparison between current/next state and props is probably the most common scenario that can give you some quick performance wins.
Example:
class UserAvatar extends Component {
render() {
return <div><img src={this.props.imageUrl} /> {{ this.props.username }} </div>
}
}
As you can see the output depends on props.imageUrl and props.username. If in a parent component you render <UserAvatar username="fabio" imageUrl="http://foo.com/fabio.jpg" /> with the same props, React would call render every time, even if the output would be exactly the same. Remember though that React implements dom diffing, so the DOM would not be actually updated. Still, performing the dom diffing can be expensive, so in this scenario it would be a waste.
If the UserAvatar component extends PureComponent instead, a shallow compare is performed. And because props and nextProps are the same, render will not be called at all.
Notes on the definition of "pure" in React:
In general, a "pure function" is a function that evaluates always to the same result given the same input. The output (for React, that's what is returned by the render method) doesn't depend on any history/state and it doesn't have any side-effects (operations that change the "world" outside of the function).
In React, stateless components are not necessarily pure components according to the definition above if you call "stateless" a component that never calls this.setState and that doesn't use this.state.
In fact, in a PureComponent, you can still perform side-effects during lifecycle methods. For example you could send an ajax request inside componentDidMount or you could perform some DOM calculation to dynamically adjust the height of a div within render.
The "Dumb components" definition has a more "practical" meaning (at least in my understanding): a dumb component "gets told" what to do by a parent component via props, and doesn't know how to do things but uses props callbacks instead.
Example of a "smart" AvatarComponent:
class AvatarComponent extends Component {
expandAvatar () {
this.setState({ loading: true });
sendAjaxRequest(...).then(() => {
this.setState({ loading: false });
});
}
render () {
<div onClick={this.expandAvatar}>
<img src={this.props.username} />
</div>
}
}
Example of a "dumb" AvatarComponent:
class AvatarComponent extends Component {
render () {
<div onClick={this.props.onExpandAvatar}>
{this.props.loading && <div className="spinner" />}
<img src={this.props.username} />
</div>
}
}
In the end I would say that "dumb", "stateless" and "pure" are quite different concepts that can sometimes overlap, but not necessarily, depending mostly on your use case.
i am not a genius over react, but from my understanding we can use each component in following situations
Stateless component -- these are the component which doesn't have life-cycle so those components should be used in rendering repeat element of parent component such as rendering the text list which just displays the information and doesn't have any actions to perform.
Pure component -- these are the items which have life-cycle and they will always return the same result when a specific set of props is given. Those components can be used when displaying a list of results or a specific object data which doesn't have complex child elements and used to perform operations which only impact itself. such a displaying list of user cards or list of products cards( basic product info) and only action user can perform is click to view detail page or add to cart.
Normal Components or Complex Components -- I used term complex component because those are usually the page level components and consists lot of children components and since each of child can behave in its own unique way so you can't be 100% sure that it will render the same result on given state. As I said usually these should be used as container components
React.Component is the default "normal" component. You declare them using the class keyword and extends React.Component. Think of them as a class, with lifecycles methods, event handlers and whatever methods.
React.PureComponent is a React.Component that implements shouldComponentUpdate() with a function that does a shallow comparison of its props and state. You have to use forceUpdate() if you know the component has props or state nested data that changed and you want to re-render. So they're not great if you need components to re-render when arrays or objects you pass as props or set in your state change.
Functional components are ones that don't have lifecycle functions. They're supposedly stateless, but they're so nice and clean that we now have hooks (since React 16.8) so you can still have a state. So I guess they're just "clean components".

Categories

Resources