Using components in React with a better understanding of how they affect your App’s Performance has always been a confusing topic, and developers end up having a bulky code base that gets harder to manage through time. So, the major answer that you will hear that Class Components provide access to more features like (state), but with Hooks that’s not valid anymore.

You must have heard about one of them having better performance, but performance depends on what the code is doing rather than choosing a class or function. The performance is almost the same and can make differences using various optimization techniques.

Function Components

Consider A Component. Let’s take an example using a simple component that simulates a network request with setTimeout and shows a confirmation alert. If props.user is ‘Mohit’ it will simply show ‘Followed Mohit’ after 3 seconds.

In the example above you can use arrows or function declaration both work the same way.

Implementing the above example in class:

Oftentimes people mistakenly look at both the same way, but there is a difference between their implications. To observe the difference you can open the code sandbox I have created for a better understanding.

Open the code sandbox given above and run the code, now try these steps to measure the difference.

Click on the follow button. (function or class you can choose any of it)

Change the selected profile before 3 seconds pass.Now read the text alert.

You will notice when we click on the follow button (using a function component) and then switch to a different profile, it shows the previous user name instead of what we selected later 3 seconds pass. But when we press the follow button (using a class component), it shows the newly selected user name every time. You will getter a better understanding by running the sandbox on your own.

In this example, if you press the follow button on ‘Mohit’s’ profile and then change the selected user you are still going to see Mohit in the alert dialogue box in case of function component. And in the case of the class component, you will notice the switched profile name in the alert dialogue box.

As you can see, the first behavior is totally what we claim to be correct for us, as my component shouldn’t get confused about who I followed!.

#javascript #we #react #react-native #coding

How to Understand the Difference Between Function & Class Components in React
3.45 GEEK