Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconEverything You Need to Know About React useCallBack()

Everything You Need to Know About React useCallBack()

Last updated:
4th Jun, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
Everything You Need to Know About React useCallBack()

Introduction to React useCallBack()

When building a website using React, it’s important to consider how fast it loads and how quickly users can interact with it. One way to make a React website faster is to prevent it from doing unnecessary work, such as re-rendering parts of the page that haven’t changed.

The useCallback() function in React helps us achieve this by remembering functions we define and only re-creating them when necessary. This can make the website faster and more responsive for users. React is the most popular front-end JavaScript library, according to a Stack Overflow survey in the same year, suggesting that useCallback() is likely widely used in the industry.

In this article, we’ll explain what is useCallBack() in React and how to use it in our React code to improve performance. 

What is useCallBack in React?

useCallback() is a hook function provided by React that is used to memoise a function. In other words, it helps to optimise the performance of a component by avoiding unwanted re-rendering.

Ads of upGrad blog

In React, when a component’s state or prop changes, the component is re-rendered to reflect the updated values. This process is computationally expensive and can decrease the application’s performance if handled improperly. This is where useCallback() comes in handy.

With useCallback(), users can memoise a function, meaning it is only redefined when its dependencies change. This prevents unnecessary component re-rendering, thereby optimising the application’s performance.

Here is an example – 

const memoizedCallback = useCallback(

  () => {

    doSomething(a, b);

  },

  [a, b],

);

 

While getting started with React through tutorials is a great way, pursuing a dynamic course to get started with development can significantly help you update your skills. Check out the Executive Post Graduate Programme in Software Development – Specialisation in Full Stack Development course from upGrad to kickstart! 

Advantages of using useCallBack()

Here are some advantages of using React useCallBack() –

  • useCallback() can help React applications run faster by preventing unnecessary updates of components.
  • If a component fetches much data and shows it as a graph, it can benefit from useCallback().
  • If the parent component of the graph updates, but the changes don’t affect the graph, there’s no need to update it and fetch the data again.
  • Using useCallback() to memoise the function fetching the data, we can avoid unnecessary updates and make the application faster and smoother.
  • This optimisation can improve the user experience, as the application will work more quickly and efficiently.

Check Out upGrad’s Software Development Courses to upskill yourself.

Syntax and Parameters of useCallBack()

const memoizedCallback = useCallback(

  () => {

    doSomething();

  },

  [dependency1, dependency2]

);

 

In the example, the useCallback() hook memoises the doSomething() function, which means it caches the previously created version. The cached function will only be used on subsequent renders unless the value of dependency1 or dependency2 changes.

If either of these dependencies changes, a new version of the doSomething() function will be created, and the cached version will be replaced with the new one. This helps optimise the application’s performance by preventing unnecessary function creations and re-renders.

Difference between useMemo() and useCallBack()

useCallback and useMemo are React Hooks that can improve the performance of a React application by memoising values. Both hooks take a function as an argument and return a memoised version of that function.

Here’s the difference between the two:

useCallbackuseMemo
ReturnsMemoised callbackMemoised value
AcceptsA function and a dependency arrayA function and a dependency array
Use caseEvent handlers, passing propsExpensive calculations or rendering
Exampleconst memoizedCallback = useCallback(() => { … }, [dependency]);const memoizedValue = useMemo(() => expensiveOperation(data), [data]);
Re-calculationOnly if one dependency has changedOnly if one dependency has changed
Helps to preventUnnecessary re-rendersUnnecessary re-computations

 

Scenarios when to use useCallBack()

Here are the scenarios when useCallBack() can be used – 

Child Components Optimization

useCallback React optimises child components that rely on reference equality to avoid unnecessary renders, especially when passing callbacks to these child components.

Preventing Unnecessary Renders

React useCallback is particularly useful when you have a component with a child element that is repeatedly rendering without needing it. You can pass a callback function and a dependency array to useCallback to prevent unnecessary renders.

Use your chance to understand the useCallBack() function in detail with the help of the Full Stack Software Development Bootcamp course from upGrad. 

Explore our Popular Software Engineering Courses

Examples of useCallBack()

Here are some examples of how to implement the useCallBack() hook.

useCallBack Example 1

When a parent component passes down a function as a prop to a child component, frequent re-rendering of the parent can cause the child component to re-render unnecessarily. In such cases, using useCallback to memoise the function that can help prevent these unnecessary re-renders.

 

import React, { useCallback } from ‘react’;

 

function ParentComponent() {

  const handleButtonClick = useCallback(() => {

    console.log(‘Button clicked’);

  }, []);

 

  return (

    <ChildComponent onClick={handleButtonClick} />

  );

}

 

function ChildComponent({ onClick }) {

  return (

    <button onClick={onClick}>Click me</button>

  );

}

useCallBack Example 2

Suppose you have a function that performs complex computations on a large dataset. If this function is called frequently and takes a long time to execute, it can cause performance issues in your application. In this scenario, you can use useCallback to memoise the function and prevent unnecessary re-execution of the computation.

 

import React, { useState, useCallback } from ‘react’;

 

function ParentComponent() {

  const [data, setData] = useState([]);

 

  const processData = useCallback(() => {

 

    const processedData = “Processed data”; 

 

    return processedData;

  }, [data]);

 

  return (

    <ChildComponent processData={processData} />

  );

}

 

function ChildComponent({ processData }) {

  const result = processData();

 

  return (

    <div>{result}</div>

  );

}

 

React Performance Optimization using useCallBack()

A useCallback hook is a powerful tool in React that allows you to memoise a function, ensuring it is only remade when one of its dependencies gets changed. This is particularly beneficial for performance-intensive functions that are called frequently. Check out the example below to see how it can be used – 

 

import { useState, useEffect } from ‘react’;

 

function App() {

  const [word, setWord] = useState(“Bob”);

  

  const say = () => console.log(`Your word is: ${word}`);

  

  useEffect(() => {

    say();

  }, [say]);

  

  return <div>Welcome!</div>;

}

 

The example demonstrates that the useEffect hook is dependent on the say function, which means it should only trigger with a change in function. Yet, due to React’s referential equality checks, say function will always evaluate to be true, even in the instance of no actual change, resulting in unnecessary renders.

The useEffect callback will be used on each render, which is not suitable for performance. One way to solve this is to relocate the function to useEffect block, but this wouldn’t be an ideal solution since you wouldn’t be able to use the function in any other place. Check out this example below – 

 

import React, { useState, useEffect } from ‘react’;

 

function App() {

  const [word, setWord] = useState(“Bob”);

 

  const say = () => console.log(`Your word is: ${word}`);

 

  useEffect(() => {

    say();

  }, [say]);

 

  return <div>Welcome!</div>;

}

 

Another solution is to implement the useCallback hook by wrapping the function. It’s essential to remember the useCallback function requires a dependency array just like useEffect. If the function takes any variables, users can pass it with the array; or else leave it empty. Here, as the say function relies on the word variable, we include it in the array.

 

import {useState, useEffect,useCallback} from ‘react’

 

function App(){

 

    const [word,setWord]=useState(“Bob”)

 

    const say = useCallback(()=>console.log(`Your word is: ${word}`),[word])

 

    useEffect(()=>{

 

        say() 

 

    },[say]) 

 

    return <div>Welcome!</div> 

}

 

When not to use useCallBack()

Ads of upGrad blog

While useCallback() is a useful tool for optimising performance in certain scenarios, there are also times when it is unnecessary or even detrimental. Here are some examples of when not to use useCallback():

  • When the function is passed as a prop is already a pure function that does not rely on an external state.
  • When the function is passed as a prop, it is not causing any performance issues and is not being called excessively.
  • When the function is passed as a prop, it is used in multiple places and needs to be re-created each time to reflect different behaviours or dependencies.
  • When the function is passed as a prop is part of a small component tree, the performance gain from useCallback() would be negligible.
  • When the function is passed as a prop is used as an event handler and is only called once.

In these cases, using useCallback() may actually decrease performance due to the overhead of creating and maintaining the memoised callback. It is important to consider each use case carefully and weigh the potential benefits against the potential costs before deciding whether or not to use useCallback().

In-Demand Software Development Skills

Conclusion

Using useCallback can be a powerful tool for optimising the performance of your React application. By memorizing functions, unnecessary re-renders can be avoided, leading to a smoother and more efficient user experience. However, it’s important to use useCallback judiciously and understand the scenarios when it is most effective. 

upGrad offers a Master of Science in Computer Science program that provides a comprehensive computer science education focusing on industry-relevant skills. This programme is for any fresher or more experienced individual to enhance their software development skills. With this course, students will be more than ready to upgrade their careers in the real world and become experts in their aspired fields. 

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What is React useCallback hook used for?

useCallback is used to optimise child components that depend on reference equality to avoid unnecessary renders, especially when passing callbacks to these child components.

2When should you not use useCallback?

useCallback should not be used when the function is already optimised or has no dependencies.

3How is useCallback different from useMemo?

useCallback memoises a function, while useMemo memoises a value. useCallback is used for functions that are often passed as props to child components, while useMemo is used to optimise expensive computations.

Explore Free Courses

Suggested Blogs

Best Jobs in IT without coding
134105
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers &#038; Experienced [2023]
900289
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers &#038; Experienced [2024]
904977
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5019
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag &#038; Attributes in HTML: Features, Uses, Examples
5127
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5047
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5112
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5049
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions &#038; Answers (Freshers &#038; Experienced)
5126
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon