React Hooks with Typescript : UseCallback, UseMemo, UseContext And UseRef

Lets, check react advanced hooks, i.e. UseCallback, UseMemo, UseRef, and UseContext. All these come under React 16.8 version and help the user create an optimized react application.

Let’s create a react application environment for our project by using either of the following commands:   

The above command will create a Project with the name “advanced-hooks-tutorial”. Once it’s done go to the directory and start the project either by “npm start” or “yarn start”.

We will be using yarn throughout this tutorial to maintain consistency.

Let’s now integrate the project with antd which is a design library by the name of antd design, that helps us to create some standard UI components. Additionally, you can use other design libraries as well if you want.

  1. Add antd to dependency

2. Add antd CSS to load stylings

That’s all for our project base, we have successfully integrated react hooks with antd design library.


UseCallback takes two arguments- In the first argument it takes an inline function that is called callback and in second arguments it takes an array of dependencies on which the callback function depends and returns a memoized callback.

The memoized callback changes only when one of its dependencies is changed. This is useful to optimize the child components that use the function reference from their parent component to prevent unnecessary rendering.

Let’s see an example for this – Here, we are going to create an app consisting of two-buttons which will increment the age and salary of a person.

  • Create a file AdvancedHooksComponent.tsx in src/components directory- create the directory if not available there.
  • Now create a functional component, ie. AdvancedHooksComponent and import the component in App.tsx file.

After this, your App.tsx file would look like :

Now let’s add two child Button component named- AgeButton, SalaryButton, and a Title component. Import them in AdvancedHooksComponent.tsx.

We have used the useState hook to create state variables, i.e. age and salary and their corresponding dispatcher, ie. setAge and setSalary. Learn How to create State Variables.

AgeHandler and SalaryHandler are two inline functions that increment the age and salary on every click of AgeButton and SalaryButton respectively.

Note: If you don’t know how to use useState then you can refer our blog from here:- React Hooks With Typescript.

AgeButton component looks like :

SalaryButton component looks like :

We have a console statement in both the AgeButton and SalaryButon that will help us in understanding the concept of useCallback hook later in the project.

Note: AgeButton and SalaryButton components are wrapped in the React.memo function which is a higher-order function. You can learn more about this from here:- React Memo.

Now start the app using the below command:

You will see the following output in the console:

Callback Example

As you can see in the web console, the rendering order of child component- first AgeButton component render and then SalaryButton component render.

Now, if we click on the increment Age Button then age will be incremented and react will re-render the component because if state changes then the component re-renders.

So the output looks like :

As you can see in the console- The AgeButton component re-render and age become 13, which is correct but the SalaryButton component also re-render and that is not necessary because we updated the age only and not salary.

So to fix this problem, useCallback comes into the picture:

We have to pass the ageHandler and salaryHandler function in the useCallback hook, so that memoized callback returns and changes only when passed dependencies changed.

For ageHandler- the only dependency is age and for salaryHandler- salary is the only dependency.

Now, if I click on the increment age button only the AgeButton component will re-render.

As you can see in the console only the AgeButton component is re-rendered. So this is how useCallback helps in preventing unnecessary rendering.


This hook will return a memoized value.

Suppose you have to compute a value that requires complex computation like fetching the list of 500 people from a database and then map over the list and then filter some person and finally update on the UI.

This operation is costly and recomputes after every rerender.

Using useMemo, we can simplify the process and this operation is performed only once and the value is stored in the cache. And the next time you want it, you’ll get it much faster.

The syntax of useMemo is similar to useCallback, but both work differently- useCallback returns a memoized callback(or function), on the other hand useMemo returns a memoized value (the result of the memoized callback).

Let’s see an example for this, where I made some modifications in AdvancedHooksComponent.tsx file :

We have the “notMemoizedValue” function, which will check whether the current age is even or odd but we need some computational work to do before checking odd or even.

For simplicity, we will make a while loop that takes some time (which behave as complex computation like fetching data from database and so on). After the while loop breaks, the odd-even checking statement executes.

The result of “notMemoizedValue” function will be displayed on the UI.

So, as you can see our “notMemoizedvalue” function returns an even value but this value is not memoized value because if we press the increment salary button then the salary will be incremented. And after this rerendering occurs which leads to the recomputation of the “notMemoizedValue” function value that remains unchanged because age doesn’t change only the salary gets changed. Apart from this, you might feel some delay also.

So, Using useMemo we can return a memoized value of the “notMemoizedValue” function which saves the time from recomputation.

Using useMemo the code will look like :

Simply, remove the “notMemoizedValue” function with “memoizedValue” function and save the file.

Now, if you again press the increment salary button then the memoized value of Odd-Even will be return by the “memoizedValue” function and now this time you do not feel any delay.


Using useRef Hook, we can access the DOM nodes or HTML elements as we access in vanilla javascript via “document” object, so that we can interact with those DOM nodes.

useRef hook takes an initial value and returns a mutable object (a mutable object means the object whose state can be changed after it is created).

The return ref object holds a mutable value in its current property which will remain the same on every rerender.

Let’s do an example for this: In the same file AdvancedHooksComponent, let’s create an input element- :

As you can see, we have an inputRef object containing initial value as null which gets passed in the input ref attribute.

Now, save the file and go to your browser- You will see that your input field is focused and you can do other things as well, as you do in vanilla javascript by “document” object.


Note: useRef does not notify you when it’s content value changes. Also changing useRef current value doesn’t lead to re-render.


To understand the concept of useContext hook– First we have to understand what is React Context API?

React Context API helps us to pass the data down to the child components (which depends on parent for data) from the root or parent component, instead of manually passing the data to every component by using props.

Let’s look at the below picture :

Suppose, we have three above components in our project and we want to pass the username of a user from AppComponent to UserComponent without using HomeComponent in between:-

App.tsx looks like :

Here, we used React.createContext API to create a Context with an empty string as the initial value. It returns two components Provider and Consumer. Learn about API.

Provider: It is used to pass the data down to the child components.

Consumer: It is used to consume the data passed by the Provider component.

Note: If you don’t use useContext hook, then you can use the Consumer component. But here we use, useContext hook for consuming the data which makes the code less and more readable.

Provider component takes an attribute called “value” through which we can pass the data down. To use the passed data value, components should be wrapped inside the UserContext component.

HomeComponent simply just renders UserComponent.

UserComponent uses the passed data value- First it imports the UserContext Object from App.tsx file, then passes this object in the argument of useContext hook (which returns the passed data value), as we have used inside the div tag.

The output of the above code looks like :

That’s it. We have successfully used useCallback, useMemo, useRef, and UseContext.

What is useCallback hook?

UseCallback help us to return a memoized callback(or function), and it prevents from re-creating a function on every re-render. It re-creates the passed function only when one of its array of dependency changed.

What is useMemo hook?

useMemo returns a memoized value. The function passed to the useMemo only recompute the function return value when one of its array of dependency changed.

What is useRef hook?

useRef is used to access the DOM nodes or HTML elements to interact with those HTML elements like accessing their value, add class name or remove class name etc. It is very similar to the “document” object as we use in vanilla javascript.

What is React Context API?

React Context API help us to pass the data down to child components without the use of manually passing the data using props.

What is useContext hook?

When we use React Context API, the code we write for data consumption is more complex and not readable. So, we use useContext Hook with the React Context API just to write less code and make code more readable.

What is memoization in useCallback and useMemo hook?

Memoization means storing the result of costly function calls in case useMemo or storing the function reference in case of useCallback so that, we can use it on every re-rendering.

Can I use React Context API without useContext hook?

Yes, you can use React Context API without useContext hook. useContext hook makes the use of data consumption easier.

What is the difference between useCallback and useMemo?

useCallback returns a memoized callback(or function), on the other hand useMemo returns a memoized value the result of the memoized callback.

How useful was this post?

Click on a star to rate it!

Leave a Comment

Your email address will not be published. Required fields are marked *