How to use UseCallback hook in react?

 Introduction

The react useCallback hook is used for the performance optimization and it memoized the function which doesn't cause the re-render of component , if one of the dependency is not changed.

You can think memoized as cached the function instance so it doesn't need to re-calculate the resource intensive function.

UseMemo and useCallback both are used for the performance optimization but the main difference between them is useMemo memoized or cached the value and the useCallback cached the function instance.

Let's look at the example of the useCallback to make it better understand by you.

In this example below , I have created a small react app where todo will be stored and the addNewTodo is the function which add the todo whenever in the todo component todo added , there is also and increment which increment the count and both todo and the count value are shown in the web browser.

So , the problem is whenever we increment the count addNewTodo function also call which render the Todo child component every time we increments the count.

To prevent this behavior , we fold the component into the React. memo() which only re-render the child component whenever some prop changes , even after wrap with this method the addNewTodo function calls and the component re-renders, this is because of some referential equality in javascript where javascript object when compared always be false even there values remains the same.

let obj1 = {1,2.3}
let obj2 = {1,2,3}
obj1==obj2 --> false

So, in this case we need to use useCallback() hook which memoized the function instance and also care about the referential equality ,

let obj1 = {1,2,3)
let obj2 = {1,2,3}

obj1 = obj2
obj1 == obj2 -->true

This is what useCallback do , it stores the function and compare the function with the cached function instance. 






Now, wrap the addNewTodo function into the useCallback hook will only re-render when the addNewTodo function changed and will not render unnecessarily.



That's how we will use UseCallback hook and it prevents the unnecessary re-render with functions . I hope this blog clears your understanding with useCallback hook and will also share the code Sandbox link so you can practically look at the implementation and play with the code.

Thank you for reading the blog post!

Comments

Popular posts from this blog

Learn React Router v6 ( Part - 2)

Why use Typescript ?

What is Single Page Application Routing ?