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

GoLang - How to check if key exists in map?

package main import "fmt" var m map[string]string func main() { m = make(map[string]string) m["foo"] = "abc" if val, ok := m["foo"]; ok { fmt.Println("foo found -", val) } else { fmt.Println("foo not found") } if val, ok := m["bar"]; ok { fmt.Println("bar found -", val) } else { fmt.Println("bar not found") } } Output: foo found - abc bar not found

How to delete commits in Git?

Suppose you have 3 commits with SHAs as follows: HEAD~0 --> Commit 3 ccccccc HEAD~1 --> Commit 2 bbbbbbb HEAD~2 --> Commit 1 aaaaaaa If you want to remove the last two commits (i.e., commits 2 and 3) and make Commit 1 as the latest commit, run the following commands: git reset --hard aaaaaaa git push origin HEAD --force Now, the commit history would be as follows: HEAD~0 --> Commit 1 aaaaaaa