Lucas White Full Stack Engineer Share





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:

1.yarn create react-app advanced-hooks-tutorial --template typescript # or 2.npx create-react-app advanced-hooks-tutorial --template typescript

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.

Add antd to dependency

# terminal yarn add antd

2. Add antd CSS to load stylings

# src/index.tsx ... import 'antd/dist/antd.css'; ...

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

UseCallback

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.

# syntax const memoizedCallback = useCallback(() => performSomething(param1, param2 ,...),[param1, param2, ...]);

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.

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.

# src/components/AdvancedHooksComponent.tsx import React from 'react'; interface Props { }; const AdvancedHooksComponent: React.FC<Props> = () => { return ( <div> Advanced Hooks Component </div> ); }; export default AdvancedHooksComponent;

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

# src/App.tsx import React from 'react'; import './App.css'; import AdvancedHooksComponent from "./components/AdvancedHooksComponent"; const App: React.FC = () => { return ( <div className="App"> <AdvancedHooksComponent/> </div> ); }; export default App;

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

# src/components/AdvancedHooksComponent.tsx import React,{useState} from 'react' import AgeButton from './AgeButton' import SalaryButton from './SalaryButton' interface Props { }; const AdvancedHooksComponent: React.FC<Props> = () => { const [age, setAge] = useState(12); const [salary, setSalary] = useState(5000); const ageHandler = () => { setAge(age+1); }; const salaryHandler = () => { setSalary(salary+500); }; return ( <div> <h1>Use CallBack Example</h1> <AgeButton clickHandler={ageHandler} age={age}/> <SalaryButton clickHandler={salaryHandler} salary={salary}/> </div> ); }; export default AdvancedHooksComponent;

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 :

# src/components/AgeButton.tsx import React from "react"; import {Button} from "antd"; interface Props { clickHandler : () => void; age : number } const AgeButton = ({ clickHandler, age } : Props ) => { console.log("Age Button Rendered Age = " + age) return ( <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Age</Button> ) }; export default React.memo(AgeButton);

SalaryButton component looks like :

# src.components/SalaryButton.tsx import React from "react"; import {Button} from "antd"; interface Props { clickHandler : () => void; salary : number; } const SalaryButton = ({ clickHandler, salary } : Props ) => { console.log("Salary Button Rendered Salary = " + salary) return ( <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Salary</Button> ) }; export default React.memo(SalaryButton);

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:

yarn start

You will see the following output in the console:

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.

# src/components/AdvancedHooksComponent.tsx import React, {useCallback, useState} from 'react'; import AgeButton from "./AgeButton"; import SalaryButton from "./SalaryButton"; interface Props { } const AdvancedHooksComponent: React.FC<Props> = () => { const [age, setAge] = useState(12); const [salary, setSalary] = useState(5000); const ageHandler = useCallback(() => { setAge(age+1); }, [age]) const salaryHandler = useCallback( () => { setSalary(salary+500); }, [salary]) return ( <div> <h1>UseCallBack Example</h1> <AgeButton clickHandler={ageHandler} age={age}/> <SalaryButton clickHandler={salaryHandler} salary={salary}/> </div> ); }; export default AdvancedHooksComponent;

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.

UseMemo

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.

# syntax const memoizedValue = useMemo( () => costlyOperation(param1 , param2, ...) , [param1, param2, ...]);

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 :

# src/components/AdvancedHooksComponent.tsx import React, {useCallback, useState} from 'react'; import AgeButton from "./AgeButton"; import SalaryButton from "./SalaryButton"; interface Props { } const AdvancedHooksComponent: React.FC<Props> = () => { const [age, setAge] = useState(12); const [salary, setSalary] = useState(5000); const notMemoizedValue = () => { // some complex computation work here.. let i = 0; while (i < 2000000000) i++; // after while break then do something here if(age % 2 === 0) return "Even"; else return "Odd"; } const ageHandler = useCallback(() => { setAge(age+1); }, [age]) const salaryHandler = useCallback( () => { setSalary(salary+500); }, [salary]) return ( <div> <h1>UseMemo Example</h1> <h3>{notMemoizedValue()}</h3> <AgeButton clickHandler={ageHandler} age={age}/> <SalaryButton clickHandler={salaryHandler} salary={salary}/> </div> ); }; export default AdvancedHooksComponent;

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 :

# src/components/AdvancedHooksComponent.tsx import React, {useCallback, useMemo, useState} from 'react'; import AgeButton from "./AgeButton"; import SalaryButton from "./SalaryButton"; interface Props { } const AdvancedHooksComponent: React.FC<Props> = () => { const [age, setAge] = useState(12); const [salary, setSalary] = useState(5000); const memoizedValue = useMemo( () => { // some complex computation work here.. // for simplicity I wrote while loop here let i = 0; while (i < 2000000000) i++; // after while break then do something here if(age % 2 === 0) return "Even"; else return "Odd"; } , [age]) const ageHandler = useCallback(() => { setAge(age+1); }, [age]) const salaryHandler = useCallback( () => { setSalary(salary+500); }, [salary]) return ( <div> <h1>UseMemo Example</h1> <h3>{memoizedValue}</h3> <AgeButton clickHandler={ageHandler} age={age}/> <SalaryButton clickHandler={salaryHandler} salary={salary}/> </div> ); }; export default AdvancedHooksComponent;

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.

UseRef

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.

# syntax const nameRef = useRef(initialValue);

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- :

# src/components/AdvancedHooksComponent.tsx import React, { useEffect, useRef} from 'react'; interface Props { } const AdvancedHooksComponent: React.FC<Props> = () => { const inputRef = useRef<HTMLInputElement>(null); useEffect(() => { if(inputRef && inputRef.current) { inputRef.current.focus(); } }, []) return ( <div> <h1>UseRef Example</h1> <input type="text" ref={inputRef} style={{width : '40%'}}/> </div> ); }; export default AdvancedHooksComponent;

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.

UseContext

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 :

# src/App.tsx import React from 'react'; import './App.css'; import HomeComponent from "./components/HomeComponent"; export const UserContext = React.createContext(''); const App: React.FC = () => { const value : string = "Codersera"; return ( <div className="App"> <UserContext.Provider value={value}> <HomeComponent/> </UserContext.Provider> </div> ); }; export default App

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.

# src/components/HomeComponent.tsx import React from 'react'; import UserComponent from "./UserComponent"; const HomeComponent = () => { return ( <UserComponent/> ); }; export default HomeComponent;

HomeComponent simply just renders UserComponent.

# src/components/UserComponent.tsx import React, { useContext} from 'react'; import { UserContext } from '../App' const UserComponent = () => { const username = useContext(UserContext); return ( <div> <h1>UseContext</h1> <div>{username}</div> </div> ); }; export default 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.

Also Try Reading React Hooks with Typescript: Use State and Use Effect in 2020.

How useful was this post? How useful was this post? Click on a star to rate it!







Submit Rating Average rating 4 / 5. Vote count: 1 No votes so far! Be the first to rate this post. Please do Rate Us and Share!





Related Blogs Kela Casey Angular Best Angular Projects for Beginners 2020 Presenting the best angular projects for beginners list that will prepare you well with the basics and practical needs in angular development. Mentioning your experience in Angular projects can make your resume stand apart from other candidates. Angular Projects for Beginners Soundnode Notepad application Data binding in forms Customer service manager Angular Bare bones project Angular... Continue Reading

Kela Casey Programming , Python Best Python IDEs & Code Editors for 2020 In this post, we’ll discuss what is an IDE/ Code editor, the difference between IDE & Code editors, and some of the best Python IDEs & code editors, along with their best features. Python is a multi-faceted programming language that has been embraced globally with open arms. Python comes with innumerable useful features of... Continue Reading

Adam Davidson Technologies Stripe vs Braintree vs PayPal: Best Payment Gateway for E-commerce In this post, we will throw some light on some of the most essential online payment systems to make it easier for you to select among Stripe vs Braintree vs Paypal, the one that best fits your business objectives and the needs of your customers. Did you know that around 50% of online shoppers... Continue Reading



About The Author Lucas is a passionate software engineer with over fifteen years of experience developing software under both web and Windows environments. He specializes in Node.js and .NET frameworks, as well as React and AngularJS on the front-end. Lucas holds a Master’s degree in computer science and has worked with a variety of Agile teams. He communicates extremely well.

Feedback Please leave a comment here and share your valuable feedback with us!

Try our One-Week Risk Free Trial for Hiring a Coder Know more Hire a Coder