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

How to install/upgrade/downgrade kubectl in Linux (Ubuntu)?

To install the latest version: curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" curl -LO "https://dl.k8s.io/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256" echo "$(<kubectl.sha256) kubectl" | sha256sum --check sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl kubectl version --client kubectl version To install a specific (v1.19.0) version: curl -LO "https://dl.k8s.io/release/v1.19.0/bin/linux/amd64/kubectl" curl -LO "https://dl.k8s.io/v1.19.0/bin/linux/amd64/kubectl.sha256" echo "$(<kubectl.sha256) kubectl" | sha256sum --check sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl kubectl version --client kubectl version This will install kubectl client. Run minikube start to install kubectl server.

Application Load Balancer (ALB)

The ALB spans all subnets in a VPC i.e., it is not inside a subnet but VPC. ALB is bound to Target Groups (TGs). TGs are bound to subnets.