Class-based components vs functional components in React (2023)

In response, there are two ways to create components. Components can be class-based or functional. As a beginner just starting to learn React, it can be a little confusing to understand when to use any of these approaches. Although both the class-based component and the functional component give the same result depending on what you want to achieve, there are still some differences between the two, and in this article we will cover the main differences between the two components.

Differences between class-based components and functional components

  • Rendering via JSX

    The noticeable difference between class and function components is syntax. A class component extends a react component that has a render method and then returns a JSX element, while a function component is a plain javascript function that returns JSX.

Class components (no destructuring)

When we write a class component, we can either extend itReact.Componentor we deconstruct and expand itComponentssama. Theto make()A method is the only required method in a class component. The check is performed every time the Render method is calledthis one. propsIthis one. Stateand returns react elements (JSX), strings and fragments etc. This does not change the status of the component.

import Answerfrom 'answerer';class application expanded Answer.Components { render() {return

Hello Welt!

; }}

Class components (with destructuring)

Destructuring is a feature of ES6 and you can learn more about ither

import Answer, {Components} from 'responder';class application expanded Components { render() {return

Hello Welt!

; }}

Functional components (with arrow functions)

Functional components can also be created using ES6's arrow function. Arrow functions are simpler and have a concise syntax for creating functions, often making them easier to use than function expressions.

You can read more about ither

import Answer from "answer";Art application= () => {return <h1>Hello world!h1>;}

Function component (using a function expression)

(Video) Class Components vs Functional Components in React (Which is better? - Beginner's Guide)

import Answer from "answer";function application() {return <h1>Hello world!h1>;}
  • pass the props

Properties stand for properties and are used as a means of communication between components, essentially passing data from parent to child. Adding props can be a bit confusing at times. Let's see how props are passed in both components.

class based component.

In a class-based component, we need to usethis oneThe keyword to access the prop or we can destroy it to get our value from the prop

import Answer, {Components} outside"answer";class Parent component expanded Components { render() {return( <> <ChildComponentto do="Sara"bee=„12“hobby ="Going on a bike"/> ); }}class ChildComponent expanded Components { render() {return( <>

MinimumThe name is {this one.props.name}

andContainer {this one.props.age} years

andlove {this one.props.hobby}

); }}// we can also destroy it so it looks like thisclass ChildComponent expanded Components { render() { const { Name, Change, Hobby } =this one.The propsreturn( <>

Minimumname is {name}

andis {age} years old

andi like {hobbies}

); }}

functional component

In the function component, the prop is passed directly to the function as an argument, and we can now access the prop usingProp-Wert.

P.S.: The value can be any.

import Answer from "answer";Art Parent component= () => {return <ChildComponent To do="Sara" Bee=„12“ Hobby="Going on a bike"/>;};Art ChildComponent= (props) => {return(<> <h4>My name is {props.name}h4> <h4>I am {props.age} years oldh4><h4>I love {props.hobby}h4>);};// with destructuringArt ChildComponent= (props) => {Art{name, age, hobby} = propsreturn(<> <h4>My name is {name}h4> <h4>I am {age} years oldh4><h4>I love {hobby}h4>);};
  • How to handle and update.

Before React 16.8 was released, state handling and updating was only possible via a class-based component. But now we can also handle state in functional components using React's useState hooks.

To understand how the state reacts, let's create a counter app that increments and decrements on a call to action. This enumeration application shows us how status is handled and updated in class and function components.

class based component

(Video) Functional Component vs Class Component In React | React Hooks

In a class-based component, we can access the state value usingthis conditionwithin JSX. You should not update the state directly, but instead use setState to update the state value.

//that's wrongthis one.country.name =„Hannah“//Do this instead this one.setState({ ime:„Hannah“});
import Answer, {Components}from "answer";class application expanded Components{ state = {count:0}; addCount =() =>{this one.setState({count:this one.stat.count+1}); }; minusTal =() =>{I(this one.stat.count<=0) {this one.setState({count:this one.stat.count}); }other things{this one.setState({count:this one.stat.count-1}); } };right() {return(<div> <Taste na klik={this.minusCount}>-Taste> <S>{this.state.count}S><Taste na klik={this.addCount}>+Taste>div>); }}

functional component

We use useState to manage state in functional components. The UseState hook gives us an array to work with. This string consists of two values: the status and the function of the setter. We update our status with this setter function. The UseState hook also takes a value for the default state.

import Answer, {useState}from "answer";function application() {Art[count, setCount] =useState(0);Art addCount= () => {setCount(count +1); };Art minusCount= () => {I(number <=0) {setCount(count); }other things{setCount(count -1); } };return(<div class name="Application"> <Taste na klik={minusCount}>-Taste> <div>{count}div><Taste na klik={addCount}>+Taste>div>);};

In the example above:countis our current state duringsetCountis a setter function that updates our state. Then we sent the onClick event to our button and it takes over the function, e.gminusCount. The setter function, which issetCountnow it is being used to devalue our state from withinminusCountFunction.

Note

The conditional statement in minusCount prevents the counter from counting negatively.

It is best to use functional components when your component is a stateless component, that is, a component that has no state.

  • Life cycle methods

Lifecycle methods are special methods built into React that manipulate components during their lifetime in the DOM. For example when a component is mounted, displayed, updated or disassembled.

class based component

(Video) React Functional Components VS Class Components Practical Differences : Part 14

There are four main types of lifecycle methods in a class-based component. These are:

  • To make: We already know that the render method is the most important lifecycle method. Each class component must contain a display method.

  • ComponentDidMount: Called when a component instance is created or inserted into the DOM. This is where we usually call our APIs, set times and also add event listeners.

  • ComponentDidUpdate: Called when a component is rendered due to changes in its properties or state. Fired when our component is updated.

  • ComponentWillUnmount: Called when the component is removed from the DOM.

import Answer, {Components} outside"answer";class Letterhead expanded Components { constructor(reqs) {super(Properties);this one.state = {favoritfarve:"Instruments"}; } ComponentDidMount() { setTimeout(() => {this one.setState({ Omiljena buoy:„gul“}) },1000) } render() {return(

Minimum favourite Coloris {this one.state.favoritfarve}

); }}

functional component

With useEffect you can trigger side effects in a function. Since we've already covered the React class lifecycle methods, you can think of the useEffect hook as a combination of componentDidMount, componentDidUpdate, and componentWillUnmount.

This is the useEffect syntax:

useEffect (() => {},[])

Inside the curly brackets you can write the code to be executed. The UseEffect hook takes another parameter, a dependency array, which only restarts the effect if the values ​​in the array change through the render gene. This allows us to adjust the frequency of the effect. Although the string of dependencies at the end of the hook is optional, it is needed more often.

(Video) React Basics Crash Course (2020): Functional Components vs Class Components

There are three ways to express a set of dependencies:

one. With an empty string appended to the end of the hook.

useEffect ( () => {//do something here},[])

That's exactly how it worksComponentDidMountand this means that the hook will be executed as soon as the component is inserted into the DOM.

b. Add an array of dependencies with a value.

This is quite similar to the example above, except that in this case the value is placed in a field, meaning that the hook is only displayed when the value changes. This is similarComponentDidUpdatefunctions.

useEffect ( () => {//do something here},[Wert])

c. Without adding a bunch of dependencies.

You can also omit a number of dependencies entirely. This way, the useEffect hook will fire whenever the component is updated and immediately after the first render. This differs from the componentDidUpdate lifecycle method as it is also executed after the first render. That way, it would correspond to a combination of componentDidMount and componentDidUpdate methods.

The return statement we add to our useEffect is actually equivalent to the ComponentWillUnmount method.

useEffect(() =>{ArtCountdown =setTimeout(() =>{// do something here},in 2000)return () =>{// Cleanup starts here clearTimeout(Timer) }})

If you write a callback statement like above in useEffect, it does the same thing as the ComponentWillUnmount method. As you can see, there is a lot behind the useEffect hook. You can also use it to make your own custom hooks.

(Video) 99% React Developers Fail to Answer THIS Question!

Continue

Using a class-based or function-based approach has its pros and cons, but I'd like to point out the following:

Functional components are easy to write, and they make our code cleaner and more readablethis oneMost of the time keywords in class components can be confusing. However, this is not a debate about whether to choose one or the other. Most of the React codebase is still heavily based on the class component, and React has stated that it will not stop supporting class components anytime soon. However, it is wise to start by introducing functional components as hooks take over in modern React.

FAQs

Is it better to use a functional component or a class component in React? ›

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."

Why use class components over functional components React? ›

The most obvious one difference is the syntax. A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. A class component requires you to extend from React. Component and create a render function which returns a React element.

When would you prefer a class component over functional component? ›

Functional Components vs Class Components
Functional ComponentsClass Components
Functional components are more efficientClass components are a little inefficient
Functional components require fewer lines of code and are easy to understandClass components are complex and require more lines of code.
7 more rows
Jan 7, 2023

Is class component outdated in React? ›

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

Should you always use functional components in React? ›

Yes functional components are better in React, with the introduction to the React hooks, we can do so much of things in functional components, even we can use lifecycle methods inside the functional component. We can even create functional components using ES6 arrow functions.

When would you use a class component over functional component in React native? ›

Class components are used as container components to handle state management and wrap child components. Functional components generally are just used for display purposes - these components call functions from parent components to handle user interactions or state updates.

Which one is better to use either class component or functional component? ›

Winner: Class Component

The functional component useEffect is confusing due to using the same hook for all the lifecycle methods. In class component, we can directly use the methods componentDidMount, componentWillUnmount, etc.

Should I use functional or class components? ›

In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props. Class Components should be preferred whenever we have the requirement with the state of the component.

What are the disadvantages of functional components in React? ›

Functional components don't support state, refs, or lifecycle methods. They can't extend PureComponent either. Sometimes, you'll create a functional component only to realize that you need one of these class-only features later.

Is React moving away from class-based components? ›

Yes, React class components will fade away in the future. If you want to embrace modern React, then you should use function components with hooks. That's why you will find most tutorials out there teaching modern React and no class components anymore.

Are class-based components dead? ›

Class components are not dead.

Do we really need class components anymore? ›

In case your current project is running on class components, don't worry, there is no harm with that. Perhaps, I would recommend using functional components over class. Nevertheless, the ReactJS community is still supporting class components and there is no hard rule to avoid them.

Are functional components the future of React? ›

The Future of Class Components

There are a great number of legacy projects which still use class components but React's team recommends using functional components for all newer projects. All the modern React tutorials also focus only on functional components.

Why functional based components are better? ›

The biggest advantage of the functional component is that they have your code easily and also make your program easy to read and understand for others.

Should I lazy load all the components in React? ›

Usually, lazy loading is not used in React applications, since we mostly use React to develop single-page applications. Developers can bundle the entire code as a single bundle and use it for deployments. But, as the application gets complex, we need to consider performance and user experience.

Can you mix functional and class components? ›

Its perfectly alright to have a mix of both functional and class components.

Can we use class component and functional component in same project? ›

You can use functional and class components in the same project. Prior to hooks being introduced, this was nearly a requirement since class components were the only ones that could hold component state and hook into life cycles.

What are the disadvantages of class component in React? ›

Also, class components have downsides;
  • Confusing (both human and machines, especially at binding and this keyword)
  • Lifecycle methods, logic spread over different lifecycle methods.
  • Hard to test compared to functional components.
  • Compiled code size and compile time.
Oct 29, 2018

When should we use functional components? ›

Developers usually used functional components if they were just rendering something and didn't need to pass state around or use lifecycle methods. Although, as mentioned before, hooks were introduced with React version 16.8. This has allowed developers to use lifecycle methods and state with functional components!

Which is better React hooks or class components? ›

Hooks allow you to use local state and other React features without writing a class. Hooks are special functions that let you “hook onto” React state and lifecycle features inside function components. Important: React internally can't keep track of hooks that run out of order.

Are functional components faster than class components? ›

It shows a greater performance than class components. The point used to measure this is made of a simple object with the type(string) and props(object) 2 properties. Rendering such a component needs to call the function and passing props.

Are functional components faster than class components React? ›

There is an opinion that functional components show a greater performance compared to class components. The point is that the React functional element is a simple object with 2 properties: type(string) and props(object). To render such a component React needs to call the function and pass props – that is all.

Can we use hooks in class components? ›

You can't use Hooks inside a class component. However, you can use HOC (Higher-Order Components) pattern to use hook logic inside existing class component.

Should I learn functional or class components? ›

Nothing is better, because both have pros and cons. But class components are important to understand React flow and lifecycle methods. The new learner should practice React using class components. Once they are familiar with class components, they can learn and use functional components.

When did React stop using classes? ›

Starting with version 16.8, React provides a way to use component and global state without the need for class components. This does not mean that Hooks are a replacement for class components, though.

Which component is best in React JS? ›

The List of the Best React Component Libraries
  • Material UI. One of the most popular React components is well known for faster and simpler web development. ...
  • Ant Design. ...
  • React-Bootstrap. ...
  • React Router. ...
  • Semantic UI React. ...
  • Blueprint UI. ...
  • React Motion. ...
  • Fluent UI.
Jan 9, 2023

Which is faster hooks or class? ›

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes. Below are code examples to illustrate React class and functional components.

Videos

1. Function Based vs Class Based Components React
(Sofia Goyal)
2. Functional Components VS Class Components in React in 2023
(Olli)
3. Using React Hooks vs. Class Components
(Ben Awad)
4. Convert functional components into class components | Class Components in React tutorial
(Scrimba)
5. Class components Vs. Functional components | Quick Reference | ReactJS | AnaghTech
(Anagh Technologies Inc.)
6. Class based vs Functional Components
(Developer)

References

Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated: 02/10/2023

Views: 6074

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.