Performance optimization is crucial for creating a smoother user experience in modern web development. React, a popular JavaScript library for building user interfaces, provides several Hooks to help developers manage state and side effects efficiently. One such Hook is useCallback()
, which plays a vital role in optimizing functional components by memoizing callback functions.
Whether you are a new React developer or someone looking to get more knowledge, this guide will provide you with insights about useCallback()
, including its syntax, usage, common use cases, and best practices. We will also compare it with another Hook, useMemo()
.
#Understanding callback functions in React
Before explaining useCallback()
, let’s start by understanding callback functions. In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some event or action has occurred.
Callback functions work the same way in the React context as in JavaScript, with the addition of being passed as props to child components. This allows children components to communicate with the parent component, enabling a flow of data and actions up the component tree.
Callback functions are an integral part of React apps as they perform activities like asynchronous operations (e.g., network requests) or handle events (e.g., clicks, form submissions, or other user interactions). For example, a button's onClick
event handler may be defined as a callback function that updates the state of a React component or performs some action when the button is clicked. Like so:
const MyComponent = () => {const [count, setCount] = useState(0);const handleClick = () => {setCount(count + 1);};return (<button onClick={handleClick}>Click me: {count}</button>);};
In this example, handleClick
is a callback function that increments the count
state whenever the button is clicked.
Looking at this example, callback functions seem really handy and do what we need them to do. So why is there a need for useCallback()
? That is because callback functions are not optimal in all cases, as we will explore in the next section.
#The problem with callback functions
Despite the usefulness of callback functions in React development, especially in handling events and interactions, they can lead to performance issues if not handled properly. The main problem stems from how React handles component re-rendering and how JavaScript treats functions as objects.
Let’s consider some common problems associated with callback functions in React:
Unnecessary re-renders
Functions are considered objects in JavaScript; as a result, every time a component renders or re-renders, any function inside that component is recreated as a new function object. This means that even if the function's logic remains exactly the same, React treats it as a new entity every time.
Consider this example:
function ParentComponent() {const [count, setCount] = useState(0);const handleClick = () => {console.log('Button clicked');};return (<div><p>Count: {count}</p><ChildComponent onClick={handleClick} /><button onClick={() => setCount(count + 1)}>Increment</button></div>);}
In this example, every time count
changes and ParentComponent
re-renders, a new handleClick
function is created. From React's perspective, this new function is different from the current render of the previous one, even though its functionality hasn't changed.
Prop comparison and child re-renders
When a new function is created and passed as a prop, React sees this as a prop change. This can trigger the parent component to re-render the child component if the child is using optimization techniques like React.memo()
or PureComponent. For example:
const ChildComponent = React.memo(({ onClick }) => {console.log('Child component rendered');return <button onClick={onClick}>Click me</button>;});
Even with React.memo
, which is designed to prevent unnecessary re-renders, the ChildComponent
will re-render every time ParentComponent
renders because it receives a "new" onClick
prop each time.
Stale closures
Callback functions can sometimes capture outdated values from their previous value, leading to bugs that are difficult to track and fix.
function Counter() {const [count, setCount] = useState(0);useEffect(() => {const timer = setInterval(() => {console.log(`Count is: ${count}`);}, 1000);return () => clearInterval(timer);}, []);return <button onClick={() => setCount(count + 1)}>Increment</button>;}
In this counter
component, the interval callback will always log 0
because it captures the initial value of count
.
These problems lead to performance implications such as:
- Cascading re-renders: In a deeply nested component tree, unnecessary re-renders can cascade down, causing significant performance overhead.
- Unnecessary computations: Each re-render involves React's reconciliation process, which can be computationally expensive, especially for complex React components.
- Increased memory usage: Creating new function instances repeatedly can lead to increased memory consumption over time.
These problems highlight the need for a way to manage callback functions in React applications. The useCallback()
is designed to address these, and we will explore it in detail in the upcoming sections.
#What is useCallback()?
useCallback()
is a part of the built-in React Hooks that optimizes the performance of React applications by preventing unnecessary re-renders of components. It achieves this through memoizing callback functions, ensuring that they are only recreated when the dependency array changes.
Syntax and parameters
The useCallback()
syntax looks like so:
const memoizedCallback = useCallback(() => {// Your callback logic here}, [dependency1, dependency2, ...]);
The useCallback()
Hook takes two arguments:
- Callback function: This is the first argument, and it represents the function to memorize (remember).
- Dependency array: This second argument is an array of dependencies that determine when the callback function should be recreated. If any value in this array changes between renders, the callback function is recreated.
How useCallback() works
After adding useCallback()
, React will memoize the provided function instance between re-renders. Here's what happens:
- On the initial render, React creates the function and returns it.
On subsequent renders, React will:
a. Check if any values in the dependency array have changed.
b. If none have changed, it returns the same function instance from the previous render.
c. If any have changed, it creates a new function instance and returns that.
This means that as long as the dependencies don't change, the exact same function instance is returned every time the component re-renders.
Let’s consider this example showing how useCallback()
works:
function ParentComponent() {const [count, setCount] = useState(0);const increment = useCallback(() => {setCount((c) => c + 1);}, []); // Empty dependency array means this function never changesreturn (<div><p>Count: {count}</p><ChildComponent onIncrement={increment} /></div>);}const ChildComponent = React.memo(({ onIncrement }) => {console.log('ChildComponent rendered');return <button onClick={onIncrement}>Increment</button>;});
In this example:
increment
is a memoized function usinguseCallback()
. It will only be recreated if the dependencies array (which are empty in this case) change.ChildComponent
is wrapped withReact.memo
to prevent unnecessary components re-render. It will only re-render if the prop changes.- Because
increment
is memoized,ChildComponent
will not re-render whencount
changes inParentComponent
.
Now that we understand useCallback()
and its proper usage, let us consider why knowing and using it might be beneficial in building React apps.
#When to use useCallback()
Here are some scenarios where using useCallback()
is particularly beneficial:
- Optimizing performance in lists: When rendering a list of items, you might need to pass a callback to each item. Using
useCallback()
ensures that the same callback instance is passed to each item, preventing unnecessary re-renders. - When a callback is a dependency in
useEffect()
: UseuseCallback()
when the callback is a dependency in auseEffect
Hook to prevent the effect from running unnecessarily. - When working with custom Hooks: Use
useCallback()
to ensure consistent function references when creating custom Hooks that return callback functions, especially if these other functions will be used as dependencies in effects. - Preventing stale closures: When a callback function depends on state or props, using
useCallback()
helps to ensure the function always has the latest values. - Passing callbacks to child components: If the function references change, the child components may re-render unnecessarily.
useCallback()
helps prevent this by memoizing the function, ensuring it only changes when its dependencies change.
#When not to use useCallback()
While useCallback()
is a powerful optimization tool, it may not be necessary in scenarios like:
- For simple React components that do not re-render often.
- When the callback is only used within the component and not passed as a prop or used in a dependency array.
- If the performance gain is negligible compared to the added complexity.
It is important to always use Hooks appropriately to prevent unnecessary complexity or performance issues in the codebase.
#How to use useCallback() - Practical examples
Everything discussed is of little use if we cannot apply the knowledge to real-world applications. As a result, we will now explore using useCallback()
in an e-commerce application. For this use case, we will focus on two functionalities:
- Adding items to "Favorites"
- Adding items to "Cart"
To do this, we will use Hygraph, a GraphQL-native headless content management system. Hygraph simplifies the development process by providing content management features while allowing developers to focus on building.
Create a React App
Set up a new React application using Vite by running the following command:
npm create vite@latest
Select React as the framework and complete the installation process. Additionally, install TailwindCSS for styling.
Start the development server using:
npm run dev
Now, check the terminal for the port the application is running on.
Setting up the Hygraph project
First, sign up for a free-forever developer account if you haven't already.
To use Hygraph in the React application, follow these steps:
- Clone the project: Clone this Hygraph eCommerce starter project to quickly set up a storefront. Once cloned, open the project.
- Configure API access: In the Hygraph project, navigate to Project Settings > API Access > Public Content API. Configure the Public Content API permissions to allow read requests without authentication. Click “Yes, initialize defaults” to add the necessary permissions for the High Performance Content API.
- Set environment variable: Locate the “High Performance Content API” and copy the URL. In the root folder of the React application, create a
.env
file and add the URL. Like so:
VITE_HYGRAPH_HIGH_PERFORMANCE_ENDPOINT=YOUR_URL
Substitute “YOUR_URL” with the appropriate URL.
Before working on the React app, explore Hygraph to understand the available content. Navigate to Hygraph’s API playground and run the query below to fetch product data, like so:
query GetProducts {products {images {idurl}namepriceid}}
This query retrieves product information accessible via the “Content” view. Now, let’s fetch and display the product data in our React application.
Fetching data from Hygraph
Navigate to the project terminal and install the GraphQL client for fetching data:
npm add graphql-request
Open App.js
and add the code below to fetch and display products:
import { useState, useEffect } from "react";import { GraphQLClient, gql } from "graphql-request";import "./App.css";const endpoint = new GraphQLClient(import.meta.env.VITE_HYGRAPH_HIGH_PERFORMANCE_ENDPOINT);const GET_PRODUCTS_QUERY = gql`query GetProducts {products {images {idurl}namepriceid}}`;function App() {const [products, setProducts] = useState([]);useEffect(() => {const fetchProducts = async () => {try {const data = await endpoint.request(GET_PRODUCTS_QUERY);setProducts(data.products);} catch (error) {console.error("Error fetching products:", error);}};fetchProducts();}, []);return (<div className="App container mx-auto p-4"><h1 className="text-2xl font-bold mb-4">Product List</h1><ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">{products.map((product) => (<likey={product.id}className="border rounded-lg p-4 shadow-md bg-gray-50"><imgsrc={product.images[0].url}alt={product.name}className="w-full object-cover mb-4 rounded bg-white"/><h2 className="text-lg font-semibold mb-2">{product.name}</h2><p className="text-gray-600 mb-2">Price: ${(product.price / 100).toFixed(2)}</p></li>))}</ul></div>);}export default App;
The code above fetches data from Hygraph using the High Performance Content API. We also used the [useState](https://hygraph.com/blog/usestate-react)
Hook, which manages the product data state, while the useEffect
handles the data fetching.
At this point, we should have a screen that looks like this:
Next, let’s add a feature to mark products as “favorites” to demonstrate the usefulness of useCallback()
.
Adding favorite “functionality”
First, install FontAwesome for icons:
npm install @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome
Update App.js
to include the useCallback()
Hook and FontAwesome icons:
import { useState, useEffect, useCallback } from "react";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { faHeart } from "@fortawesome/free-solid-svg-icons";
In this case, we are using the heart
icon to demonstrate the favorite in the UI.
Next, we will add a state:
const [favorites, setFavorites] = useState({});
This initializes the state variable favorites
as an empty object and provides a function setFavorites
to update the state. This function object allows toggling between two states, such as “favorited” or “not favorited”.
Next, we will declare the useCallback()
:
const handleFavorite = useCallback((id) => {setFavorites((prevFavorites) => ({...prevFavorites,[id]: !prevFavorites[id],}));}, []);
Here, we achieved the following:
- We wrapped the
handleFavorite
function in auseCallback()
to memoize it to prevent unnecessary re-creations on re-renders. This is especially beneficial for performance should the product item get larger applications with many products. - The function also toggled the favorite status of a product by updating the
favorites
state.
Now, we will complete this by adding the code below the “Price”:
<buttonclassName="text-xl mr-2 heart-button"onClick={() => handleFavorite (product.id)}><FontAwesomeIconicon={faHeart}style={{ color: favorites[product.id] ? "red" : "grey" }}/></button>
Here, we ensured that:
- When a user clicks the button, it triggers the
handleFavorite
function declared earlier with the product's ID. - The color of the heart icon changes based on the favorite status stored in the
favorites
state object.
Now, we should be able to see a favorite icon in the UI for each product.
Using the useCallback()
Hook here to toggle favorites on each product helps prevent unnecessary re-creations of the handleFavorite
function on re-renders. This optimization is crucial in scenarios with many items. Now let us add the “add to cart functionality”.
Implementing “add to cart” feature
First, update the FontAwesome imports to include shopping cart icons:
import {faHeart,faCartShopping,faPlus,faMinus,} from "@fortawesome/free-solid-svg-icons";
Add state and functions for handling the cart:
const [cart, setCart] = useState({});const handleAddToCart = useCallback((product) => {setCart((prevCart) => {const quantity = prevCart[product.id]? prevCart[product.id].quantity + 1: 1;return {...prevCart,[product.id]: { ...product, quantity },};});}, []);const handleRemoveFromCart = useCallback((productId) => {setCart((prevCart) => {if (!prevCart[productId]) return prevCart;const newQuantity = prevCart[productId].quantity - 1;if (newQuantity > 0) {return {...prevCart,[productId]: { ...prevCart[productId], quantity: newQuantity },};} else {const newCart = { ...prevCart };delete newCart[productId];return newCart;}});}, []);
Here, we have two functions doing the following:
handleAddToCart
: This function adds a product to the cart or increments its quantity if it already exists.handleRemoveFromCart
: This function decrements the quantity of a product in the cart or removes it if the quantity reaches 0.
Both functions use useCallback()
to memoize the function and setCart
to update the cart state.
Update the file to include cart controls:
<div className="flex justify-center items-center mt-3"><FontAwesomeIcon icon={faCartShopping} className="mr-2" /><buttonclassName=" bg-gray-300 hover:bg-gray-400 rounded-full px-1"onClick={() => handleAddToCart(product)}><FontAwesomeIcon icon={faPlus} /></button><span className="mx-2">{cart[product.id] ? cart[product.id].quantity : 0}</span><buttonclassName=" bg-gray-300 hover:bg-gray-400 rounded-full px-1"onClick={() => handleRemoveFromCart(product.id)}><FontAwesomeIcon icon={faMinus} /></button></div>
Finally, add a section to display the cart contents:
<div className="cart mt-8 p-4 border-t"><h2 className="text-xl font-bold">Cart ({Object.keys(cart).length} items)</h2><ul className="mt-2">{Object.values(cart).map((item, index) => (<li key={index} className="mb-2 flex justify-between"><span>{item.name} - ${(item.price / 100).toFixed(2)}</span><span>Quantity: {item.quantity}</span></li>))}</ul></div>
Your UI should now look like this:
Using useCallback()
in this application helps improve performance as the number of products and interactions increases. It ensures that functions handling the internal state updates are not recreated unnecessarily.
You can access the code on GitHub.
#[object Object], vs. ,[object Object]
In React, both useCallback()
and useMemo()
are Hooks that optimize performance by memoizing values and functions, but they serve different purposes and are used in different scenarios.
With a syntax that looks like the below, useMemo()
accepts two arguments (similar to useCallback()
):
- a function to calculate
- a dependency array
const memoizedValue = useMemo(() => computeExpensiveValue(a, b),[a, b], // Dependency array);
When comparing useCallback()
with useMemo()
, the differences are best based on what they memoize, return, and their use cases, as this sometimes shows the mistaken line between the two Hooks.
Considerations | useCallback() | useMemo() |
---|---|---|
What they memoize | Memoizes a callback function | Memoizes computed value |
Return value | Returns a memoized callback function | Returns a memoized value (which can be a new value of any type) |
Use | Typically for optimizing child component re-renders and in dependency arrays of other Hooks | For expensive, complex calculations and creating objects that should remain stable |
Consider this useMemo()
example:
import React, { useMemo } from 'react';const computeExpensiveValue = (a, b) => {console.log('Computing expensive value...');let result = 0;for (let i = 0; i < 1000000000; i++) {result += a + b;}return result;};const App = () => {const a = 5;const b = 10;const expensiveValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);console.log(`Expensive value for a=${a} and b=${b}: ${expensiveValue}`);return null;};export default App;
In this example, useMemo()
memoizes the result of computeExpensiveValue()
. The computation will only re-run if a
or b
changes, avoiding unnecessary recalculations on every render. This is in contrast to useCallback()
, where the function itself would be memoized, but the expensive computation would still run every time the function is called, even if a
and b
haven't changed.
Now that we have explored the difference between useCallback()
and useMemo()
, let’s consider when it is best to use useCallback()
.
#Best practices for using ,[object Object]
- Like any other Hook,
useCallback()
should only be used at the top level of the component and outside of any loop or condition. - Pair
useCallback()
with[React.memo()](https://hygraph.com/blog/react-memo)
for child components to prevent unnecessary re-renders when the callback function's reference hasn't changed. - The dependency array is crucial, and omitting necessary dependencies can cause bugs. In the dependency array, include all values from the component scope that the callback function depends on.
- It goes without saying that
useCallback()
should only be used if and when necessary. As such, only useuseCallback()
when the performance benefit is obvious.
#Conclusion
This guide provides an overview of the React useCallback
Hook, from the problem it solves to its use cases and best practices for its implementation.
Join the Hygraph developer workspace to discover exciting innovations and connect with other developers. It’s also a great place to interact with the Hygraph team, share insights, and expand your skills.
Blog Author
Motunrayo Moronfolu
Technical writer
Motunrayo Moronfolu is a Senior Frontend Engineer and Technical writer passionate about building and writing about great user experiences.