React Component Performance | Best way of method binding | Using Class or Functional Component approach

Making a component performance efficient irrespective which UI technology (React, Angular etc.) is used is always desired and every software engineer would like to do all the time.

In React, while creating a component and start binding a method to component’s template looks very easy but sometimes it could be very costly if method binding best technique is not used.

Let’s see what could be the issue if method binding is done with out implementing the best technique and how we could improve it.

In React, since a component can be created using Class or Functional approach so we will discuss both.

1. React Class Component Approach

Let’s assume we have a simple counter component which keeps track of increment or decrement of a count field:

In the above code, we you could see that Increment/Decrement buttons increase and decrease the count val. And also we have kept methods set declared outside of the component class just to keep track how many instances created of callIncrement method.

If you try to execute above code than you will observed that if Increment button is clicked 4 times than below line will be rendered:

callIncrement method created count: 4

That means you can imagine if this button is click 100 times than 100 callIncrement function instances will be created which is very bad.

Then how we can fix this issue?

Here is the code to fix this issue:

If you try to execute the above code then you will observed that if Increment button is clicked 4 times than the below line will be rendered:

increment method created count: 1

That means how many times Increment button is clicked, only 1 instance of increment method will be created.

And here are the magic lines are attached below:

2. React Functional Component Approach

Let’s assume we have a simple counter component which keeps track of increment or decrement of a count field:

If you try to execute above code than you will observed that if Increment button is clicked 4 times than below line will be rendered:

increment method created count: 4

That means you can imagine if this button is click 100 times than 100 increment function instances will be created which is very bad.

Then how we can fix this issue?

Here is the code to fix this issue:

If you try to execute the above code then you will observed that if Increment button is clicked 4 times than the below line will be rendered:

increment method created count: 1

That means how many times Increment button is clicked, only 1 instance of increment method will be created.

And here are the magic lines are attached below:

where React.useCallback() is one of the React Hook which used to store function reference.

We also have another similar hook that is React.useMemo().

I hope this article would help you to further improve the React Component performance.

Coder