Skip to main content

useCallback hook

Check the code below:

usecallback-demo-1-component-renders-unnecessarily - Code

You can run the app directly:

usecallback-demo-1-component-renders-unnecessarily - App

Whenever the button is clicked, the 'increment rendered' message is logged in console. This means, we're rendering the Increment component unnecessarily.

The Increment component is rendered every time Ã  because it depends on increment method Ã  this method again depends on count state Ã  so, whenever the count state changes, since count state is a dependency of Increment component, this must be rendered everytime.

However, consider the following code where this problem is solved (of course using random number instead of count for demo):

usecallback-demo-2-usecallback-prevents-unnecessary-renders - Code

Here, we're caching the increment method using useCallback hook. The Increment component is not rendered every time. It is rendered only on the initial load.

According to Hooks documentation, useCallback returns a memoized callback.

What does that mean? It means, it returns cached result.

Is that true? In that case, it should always return the same random number when we click the button but we get different values.

So, the above definition should be – it returns cached method (not cached value). This is the reason why though the increment method is called multiple times, the Increment component is rendered only once Ã  because, the Increment component is not dependent on any of the variables inside the increment method (Random is not a dependency but count state is), and it is happy to cache the entire method (callback).

usecallback-demo-2-usecallback-prevents-unnecessary-renders - App

Courtesy: Thanks to this Youtube Video

Comments

Popular posts from this blog

AWS Route53 - Private Hosted Zone

AWS - Error - An error occurred (ExpiredToken) when calling the DescribeStacks operation: The security token included in the request is expired

Error:   An error occurred (ExpiredToken) when calling the DescribeStacks operation: The security token included in the request is expired. Reason: It occurred when I ran a MAKE command with a profile having expired token (security credentials) Fix: Generate new security credentials (aws sts assume-role) and run the command again

AWS CloudTrail

AWS CloudTrail is an API monitoring service.  It records activities in your account. We can log those activities in S3 bucket It gives visibility to user activities e.g., if you want to know who created an EC2 instance, you can get the answer using CloudTrail Using CloudTrail, you can track changes to AWS resources in your accounts