Open In App

React useCallback Hook

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

React useCallback hook returns a memoized function to reduce unnecessary callbacks. This useCallback hook is used when you have a component in which the child is rerendering again and again without need.

React useCallback Hook

Pass an inline callback and an array of dependencies, useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

React useCallback Hook Syntax:

const memoizedCallback = useCallback(
() => {
doSomething(a, b);
}, [a, b],
);

React useCallback Hook Usage

  • This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
  • It improves the performance by reducing the unnecessary computations and providing already stored callback.
  • It is similar to React useMemo Hook, the difference is it returns a callback and useMemo returns a value.

Note: Memoization is like storing the values as cache that need not to be calculated again and again.

Without using the useCallback Hook

The problem is that once the counter is updated, all three functions are recreated again. The alert increases by three at a time but if we update some states all the functions related to that states should only re-instantiated. If another state value is unchanged, it should not be touched.

Example without the useCallback Hook:

This example creates a counter app without using the useCallback Hook.

Javascript




// Filename - App.js
 
import React, { useState, useCallback } from 'react';
const funccount = new Set();
const App = () => {
 
 
  const [count, setCount] = useState(0)
  const [number, setNumber] = useState(0)
 
  const incrementCounter = () => {
    setCount(count + 1)
  }
  const decrementCounter = () => {
    setCount(count - 1)
  }
   
   const incrementNumber = () => {
    setNumber(number + 1)
  }
   
funccount.add(incrementCounter);
funccount.add(decrementCounter);
funccount.add(incrementNumber);
alert(funccount.size);
 
  return (
    <div>
      Count: {count}
      <button onClick={incrementCounter}>
        Increase counter
      </button>
      <button onClick={decrementCounter}>
         Decrease Counter
      </button>
      <button onClick={incrementNumber}>
        increase number
      </button>
    </div>
  )
}
 
 
export default App;


This example has a problem of re-rendering even when the props aren.t changed. This can be solved by using the useCallback Hook.

Using React useCallback Hook

To solve this problem we can use the useCallback hook.

React useCallback Hook Example:

This example demonstrate the use of useCallback Hook.

Javascript




// Filename - App.js
 
import React, { useState, useCallback } from "react";
var funccount = new Set();
const App = () => {
    const [count, setCount] = useState(0);
    const [number, setNumber] = useState(0);
 
    const incrementCounter = useCallback(() => {
        setCount(count + 1);
    }, [count]);
    const decrementCounter = useCallback(() => {
        setCount(count - 1);
    }, [count]);
    const incrementNumber = useCallback(() => {
        setNumber(number + 1);
    }, [number]);
 
    funccount.add(incrementCounter);
    funccount.add(decrementCounter);
    funccount.add(incrementNumber);
    return (
        <div
            style={{
                display: "flex",
                flexDirection: "column",
                textAlign: "center",
                justifyContent: "end",
                margin: "auto",
                marginTop: "20px",
                width: "350px",
                padding: "50px",
                height: "300px",
                fontSize: "20px",
                boxShadow: "0px 2px 8px 4px grey",
                borderRadius: "5px",
            }}
        >
            {" "}
            <h2 style={{ color: "green" }}>
                GeeksforGeeks
            </h2>
            <h4>React Example for useCallback Hook</h4>
            <p>Count: {count}</p>
            <p>Function Count: {funccount.size}</p>
            <button onClick={incrementCounter}>
                Increase counter
            </button>
            <button onClick={decrementCounter}>
                Decrease Counter
            </button>
            <button onClick={incrementNumber}>
                Increase number
            </button>
        </div>
    );
};
 
export default App;


Output: As we can see from the below output when we change the state ‘count’ then two functions will re-instantiated so the set size will increase by 2 and when we update the state ‘number’ then only one function will re-instantiated and the size of the set will increase by only one.

React useCallback Hook Example - Output



Similar Reads

What's the useCallback hook used for in React Hooks?
The useCallback hook in React Hooks is used to optimize the performance of your React applications. It's helpful when you have a function that you want to pass down to child components, but you don't want those child components to re-render unnecessarily every time the parent component re-renders. Benefits of useCallback Hook in React Hooks:Perform
2 min read
Benefits of using useCallback Hook in React
The "useCallback" is a React Hook for optimizing performance in React functional components. "useCallback" can be utilized to enhance the performance of React applications by memorizing the callback function and minimizing unnecessary re-renders of components. What is useCallback Hook?In React, the "useCallback" hook memorizes a callback function.
3 min read
Purpose of useCallback hook
The useCallback hook in React is used to memoize functions, which means it returns a memoized version of the callback function that only changes if one of the dependencies has changed. Its primary purpose is to optimize performance by avoiding unnecessary re-renders in components that rely on callback functions as dependencies. Syntax:const memoize
1 min read
How can you use useCallback to memoize functions in a React component?
In ReactJS, the useCallback hook is used to memoize functions so that they are not recreated on every render unless their dependencies change. This can be useful for optimizing performance in scenarios where we are passing functions down to child components as props, especially when those functions rely on props or state values. Prerequisites: Reac
2 min read
When to use useCallback, useMemo and useEffect ?
The useCallback, useMemo, and useEffect are used to optimize the performance of React-based applications between rerendering of the components. To answer when to use useCallBack, useMemo, and useEffect, we should know what exactly they do and how they are different. PrerequisitesJavaScript and ES6+Concept of rendering Hook lifecycleuseCallback: The
8 min read
Optimizing Performance with useMemo and useCallback Hooks
In React applications, optimizing performance is crucial for ensuring smooth user experiences, especially in components with complex computations or frequent re-renders. Two hooks provided by React, useMemo, and useCallback, offer efficient ways to achieve performance improvements by memoizing values and callback functions, respectively. Table of C
4 min read
React JS useRef Hook
In this article we will learn about the useRef hook in React, its implementation and uses with the help of an example What is useRef hook?The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.The useRef hook is a new addition in React 16.8. To learn useRef the user should be aware about refs
2 min read
React.js useImperativeHandle Additional Hook
The useImperativeHandle hook works in the similar phase of useRef hook but only it allows us to modify the instance that is going to be passed with the ref object which provides a reference to any DOM element. Although this hook is used in rare cases, it has some most advanced functionality. Syntax: useImperativeHandle(ref, createHandle, [deps]) Cr
2 min read
Replacement of useHistory hook in React
In this article, we will learn how to replace the useHistory hook in React. With the introduction of new versions of React Hooks, useNavigate in React replaced the useHistory hook. useNavigate hook is a React hook that allows you to navigate your application imperatively. Table of Content What is useHistory hook?What is useNavigate hook?Why useHist
3 min read
Does React useState Hook update immediately ?
React, a widely used JavaScript library for building user interfaces, emphasizes a straightforward approach for creating dynamic web applications. React's state management system, including the useState hook, is pivotal for efficiently tracking and updating application data. Table of Content How we can use the useState hook in React?How hook update
2 min read