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

Top 22 Best Agile Project Management Tools in 2023
5002
The recent years have seen a surge in using the best Agile management tools and techniques, especially in software development. Breaking down projects
Read More

by Pavan Vadapalli

27 Sep 2023

Scrum Master Roles and Responsibilities: Everything You Should Know
5002
In today’s fast-paced business environment, organisations constantly seek ways to enhance their productivity, collaboration, and product quality
Read More

by Pavan Vadapalli

27 Sep 2023

CSM vs PSM: Difference Between CSM and PSM
5000
Staying ahead of the curve is critical in the fast-paced world of Agile project management. Certified Scrum Master vs Professional Scrum Master are tw
Read More

by Pavan Vadapalli

24 Sep 2023

How to Become a Scrum Master in 2023
5000
In the fast-paced modern business landscape, Scrum Masters have emerged as important facilitators of efficient business practices. Professional Scrum
Read More

by Pavan Vadapalli

24 Sep 2023

Agile Modeling: Core Principles, Pros and Cons
5000
Agile methodology, developed in 2001, is based on the most distinguished Agile manifesto, which introduced the core practices and principles. The Agil
Read More

by Pavan Vadapalli

24 Sep 2023

5 Core Scrum Values and Principles &#038; Why are they important
5000
The Scrum methodologies are one of the most widely used project management frameworks today. This technique adds structure to complex projects, promot
Read More

by Pavan Vadapalli

24 Sep 2023

Scrum Master vs Product Owner: Differences &#038; Similarities
5000
In Agile project management, two pivotal roles, the Product Owner and Scrum Master, play distinct yet equally vital parts within Scrum methodology.  T
Read More

by Pavan Vadapalli

22 Sep 2023

Sprint Planning in Agile Methodology: Its Importance and Benefits
5000
Sprint planning is a pivotal event in the Scrum framework, serving as the launchpad for each sprint in Agile development.  It entails the active parti
Read More

by Pavan Vadapalli

22 Sep 2023

Scrum of Scrums: Purpose, Agenda and Best Practices
5000
The Scrum of Scrums, pioneered by Jeff Sutherland and Ken Schwaber in 1996, is a vital scaled Agile technique designed to facilitate collaboration amo
Read More

by Pavan Vadapalli

22 Sep 2023

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