In this article I am going to discuss about the useCallback hook but before that if you have not read about the useMemo hook in react then must read it before reading about the useCallback hook. The useCallback hook in React is used for memoizing callback functions to optimize performance, especially in scenarios where a component renders frequently. It is particularly useful when passing callbacks to child components, as it can prevent unnecessary re-renders of those child components. The primary purpose of useCallback is to memoize a callback function and return a memoized version of that function that only changes if one of the dependencies in the dependency array changes. This can help in avoiding the recreation of the callback function on every render, which can be important for performance.

Difference between useMemo and useCallback hook

The useMemo hook is used to cache the function result so it is changed automatically when the dependency changes that we have passed in the useMemo function but on the other hand useCallback hook is used to cache the whole function. In simple words , useCallback is a React Hook that lets you cache a function definition between re-renders. Basically useCallback is used for performance optimization that makes your website more faster.

When to use the useCallback hook?

Again, The useCallback hook is a react hook, so you can only call it at the top level of your component. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it. Let see the simple example of how can optimize our code by using useCallback hook in our component.

import React, { useState, useCallback } from 'react';

const ClickCounter = () => {
  const [count, setCount] = useState(0);

  // useCallback memoizes the increment function
  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty dependency array means the callback is created only once

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

export default ClickCounter;

In above example, the increment function is wrapped with useCallback. The empty dependency array [] indicates that the callback does not depend on any external variable but if you want then you can pass the dependency as well. This means that the increment function is memoized and will not be recreated on each render unless any of its dependencies change. This can be beneficial in scenarios where the component re-renders frequently but the callback remains the same.

Conclusion

In this react hooks tutorial I have discussed about useCallback hook with detail example. Hope you found this article helpful. In the next article I going to discuss about the useReducer hook in detail.