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.
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:
useCallback | useMemo | |
Returns | Memoised callback | Memoised value |
Accepts | A function and a dependency array | A function and a dependency array |
Use case | Event handlers, passing props | Expensive calculations or rendering |
Example | const memoizedCallback = useCallback(() => { … }, [dependency]); | const memoizedValue = useMemo(() => expensiveOperation(data), [data]); |
Re-calculation | Only if one dependency has changed | Only if one dependency has changed |
Helps to prevent | Unnecessary re-renders | Unnecessary 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()
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.Â
What 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.
When should you not use useCallback?
useCallback should not be used when the function is already optimised or has no dependencies.
How 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.